Example usage for android.os SystemClock elapsedRealtime

List of usage examples for android.os SystemClock elapsedRealtime

Introduction

In this page you can find the example usage for android.os SystemClock elapsedRealtime.

Prototype

@CriticalNative
native public static long elapsedRealtime();

Source Link

Document

Returns milliseconds since boot, including time spent in sleep.

Usage

From source file:com.android.tv.settings.accessories.AddAccessoryActivity.java

protected void updateView() {
    if (mActionView == null || mStartTime == 0) {
        // view not yet ready, update will happen on first layout event
        return;//from  ww w.  ja va  2  s  .c o  m
    }

    synchronized (mLock) {
        int prevNumDevices = mActions.size();
        mActions.clear();

        if (mActionFragment != null && mBtPairer != null) {
            // Add entries for the discovered Bluetooth devices
            for (BluetoothDevice bt : mBtDevices) {
                String title = bt.getName();
                String desc;
                if (mCurrentTargetAddress.equalsIgnoreCase(bt.getAddress())
                        && !mCurrentTargetStatus.isEmpty()) {
                    desc = mCurrentTargetStatus;
                } else if (mCancelledAddress.equalsIgnoreCase(bt.getAddress())) {
                    desc = getString(R.string.accessory_state_canceled);
                } else {
                    desc = bt.getAddress();
                }
                mActions.add(
                        new Action.Builder().key(KEY_BT_DEVICE).title(title).description(desc.toUpperCase())
                                .drawableResource(AccessoryUtils.getImageIdForDevice(bt)).build());
            }
        }

        // Update the main fragment.
        ActionAdapter adapter = (ActionAdapter) mActionFragment.getAdapter();
        if (adapter != null) {
            adapter.setActions(mActions);
        }

        if (!mActionsVisible && mActions.size() > 0) {
            mActionsVisible = true;
            long delay = ANIMATE_IN_DELAY - (SystemClock.elapsedRealtime() - mStartTime);
            if (delay > 0) {
                // Make sure we have a little bit of time after the activity
                // fades in
                // before we animate the actions in
                mActionView.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        animateActionsIn();
                    }
                }, delay);
            } else {
                animateActionsIn();
            }
        }

        if (mNoInputMode) {
            if (DEBUG)
                Log.d(TAG, "stopping auto-exit timer");
            mAutoExitHandler.removeCallbacks(mAutoExitRunnable);
            if (mActions.size() == 1 && prevNumDevices == 0) {
                // first device added, start counter for autopair
                mMsgHandler.sendEmptyMessageDelayed(MSG_START_AUTOPAIR_COUNTDOWN, TIME_TO_START_AUTOPAIR_COUNT);
            } else {

                // Start timer count down for exiting activity.
                if (DEBUG)
                    Log.d(TAG, "starting auto-exit timer");
                mAutoExitHandler.postDelayed(mAutoExitRunnable, EXIT_TIMEOUT_MILLIS);

                if (mActions.size() > 1) {
                    // More than one device found, cancel auto pair
                    cancelPairingCountdown();

                    if (!mShowingMultiFragment && !mFragmentTransactionPending) {
                        if (mActionsAnimationDone) {
                            switchToMultipleDevicesFragment();
                        } else {
                            mFragmentTransactionPending = true;
                        }
                    }
                }
            }
        }
    }
}

From source file:gpsalarm.app.service.PostMonitor.java

private void setAlarm(long period) {
    alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + period, pi);
}

From source file:com.suning.mobile.ebuy.lottery.network.util.Caller.java

/**
 * /*  ww w .j a v  a 2 s  . c o m*/
 * @Description:
 * @Author:12072565 
 * @Date 2013-5-6
 * @return void
 */
private void updateRunning() {
    isFirst = false;
    timeFirst = SystemClock.elapsedRealtime();
    mHandler.sendMessageDelayed(Message.obtain(mHandler, 2), 1000);

}

From source file:goo.TeaTimer.TimerActivity.java

/**
 * Starts the timer at the given time//w  w  w  .j a  v a 2 s . c o m
 * @param time with which to count down
 * @param service whether or not to start the service as well
 */
private void timerStart(int time, boolean service) {
    if (LOG)
        Log.v(TAG, "Starting the timer...");

    // Star external service
    enterState(RUNNING);

    if (service) {
        if (LOG)
            Log.v(TAG, "Starting the timer service ...");
        Intent intent = new Intent(getApplicationContext(), TimerReceiver.class);
        intent.putExtra("SetTime", mLastTime);
        mPendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);
        mAlarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + time,
                mPendingIntent);
    }

    // Internal thread to properly update the GUI
    mTimer = new Timer();
    mTime = time;
    mTimer.scheduleAtFixedRate(new TimerTask() {
        public void run() {
            timerTic();
        }
    }, 0, TIMER_TIC);

    aquireWakeLock();
}

From source file:com.android.messaging.datamodel.action.SyncMessagesAction.java

/**
 * Perform local database updates and schedule follow on sync actions
 *//*from   www .  j a  v a 2 s . c  om*/
@Override
protected Object processBackgroundResponse(final Bundle response) {
    final long lastTimestampMillis = response.getLong(BUNDLE_KEY_LAST_TIMESTAMP);
    final long lowerBoundTimeMillis = actionParameters.getLong(KEY_LOWER_BOUND);
    final long upperBoundTimeMillis = actionParameters.getLong(KEY_UPPER_BOUND);
    final int maxMessagesToUpdate = actionParameters.getInt(KEY_MAX_UPDATE);
    final long startTimestamp = actionParameters.getLong(KEY_START_TIMESTAMP);

    // Check with the sync manager if any conflicting updates have been made to databases
    final SyncManager syncManager = DataModel.get().getSyncManager();
    final boolean orphan = !syncManager.isSyncing(upperBoundTimeMillis);

    // lastTimestampMillis used to indicate failure
    if (orphan) {
        // This batch does not match current in progress timestamp.
        LogUtil.w(TAG, "SyncMessagesAction: Ignoring orphan sync batch for messages from "
                + lowerBoundTimeMillis + " to " + upperBoundTimeMillis);
    } else {
        final boolean dirty = syncManager.isBatchDirty(lastTimestampMillis);
        if (lastTimestampMillis == SYNC_FAILED) {
            LogUtil.e(TAG, "SyncMessagesAction: Sync failed - terminating");

            // Failed - update last sync times to throttle our failure rate
            final BuglePrefs prefs = BuglePrefs.getApplicationPrefs();
            // Save sync completion time so next sync will start from here
            prefs.putLong(BuglePrefsKeys.LAST_SYNC_TIME, startTimestamp);
            // Remember last full sync so that don't start background full sync right away
            prefs.putLong(BuglePrefsKeys.LAST_FULL_SYNC_TIME, startTimestamp);

            syncManager.complete();
        } else if (dirty) {
            LogUtil.w(TAG, "SyncMessagesAction: Redoing dirty sync batch of messages from "
                    + lowerBoundTimeMillis + " to " + upperBoundTimeMillis);

            // Redo this batch
            final SyncMessagesAction nextBatch = new SyncMessagesAction(lowerBoundTimeMillis,
                    upperBoundTimeMillis, maxMessagesToUpdate, startTimestamp);

            syncManager.startSyncBatch(upperBoundTimeMillis);
            requestBackgroundWork(nextBatch);
        } else {
            // Succeeded
            final ArrayList<SmsMessage> smsToAdd = response.getParcelableArrayList(BUNDLE_KEY_SMS_MESSAGES);
            final ArrayList<MmsMessage> mmsToAdd = response.getParcelableArrayList(BUNDLE_KEY_MMS_MESSAGES);
            final ArrayList<LocalDatabaseMessage> messagesToDelete = response
                    .getParcelableArrayList(BUNDLE_KEY_MESSAGES_TO_DELETE);

            final int messagesUpdated = smsToAdd.size() + mmsToAdd.size() + messagesToDelete.size();

            // Perform local database changes in one transaction
            long txnTimeMillis = 0;
            if (messagesUpdated > 0) {
                final long startTimeMillis = SystemClock.elapsedRealtime();
                final SyncMessageBatch batch = new SyncMessageBatch(smsToAdd, mmsToAdd, messagesToDelete,
                        syncManager.getThreadInfoCache());
                batch.updateLocalDatabase();
                final long endTimeMillis = SystemClock.elapsedRealtime();
                txnTimeMillis = endTimeMillis - startTimeMillis;

                LogUtil.i(TAG,
                        "SyncMessagesAction: Updated local database " + "(took " + txnTimeMillis
                                + " ms). Added " + smsToAdd.size() + " SMS, added " + mmsToAdd.size()
                                + " MMS, deleted " + messagesToDelete.size() + " messages.");

                // TODO: Investigate whether we can make this more fine-grained.
                MessagingContentProvider.notifyEverythingChanged();
            } else {
                if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                    LogUtil.d(TAG, "SyncMessagesAction: No local database updates to make");
                }

                if (!syncManager.getHasFirstSyncCompleted()) {
                    // If we have never completed a sync before (fresh install) and there are
                    // no messages, still inform the UI of a change so it can update syncing
                    // messages shown to the user
                    MessagingContentProvider.notifyConversationListChanged();
                    MessagingContentProvider.notifyPartsChanged();
                }
            }
            // Determine if there are more messages that need to be scanned
            if (lastTimestampMillis >= 0 && lastTimestampMillis >= lowerBoundTimeMillis) {
                if (LogUtil.isLoggable(TAG, LogUtil.DEBUG)) {
                    LogUtil.d(TAG,
                            "SyncMessagesAction: More messages to sync; scheduling next " + "sync batch now.");
                }

                // Include final millisecond of last sync in next sync
                final long newUpperBoundTimeMillis = lastTimestampMillis + 1;
                final int newMaxMessagesToUpdate = nextBatchSize(messagesUpdated, txnTimeMillis);

                final SyncMessagesAction nextBatch = new SyncMessagesAction(lowerBoundTimeMillis,
                        newUpperBoundTimeMillis, newMaxMessagesToUpdate, startTimestamp);

                // Proceed with next batch
                syncManager.startSyncBatch(newUpperBoundTimeMillis);
                requestBackgroundWork(nextBatch);
            } else {
                final BuglePrefs prefs = BuglePrefs.getApplicationPrefs();
                // Save sync completion time so next sync will start from here
                prefs.putLong(BuglePrefsKeys.LAST_SYNC_TIME, startTimestamp);
                if (lowerBoundTimeMillis < 0) {
                    // Remember last full sync so that don't start another full sync right away
                    prefs.putLong(BuglePrefsKeys.LAST_FULL_SYNC_TIME, startTimestamp);
                }

                final long now = System.currentTimeMillis();

                // After any sync check if new messages have arrived
                final SyncCursorPair recents = new SyncCursorPair(startTimestamp, now);
                final SyncCursorPair olders = new SyncCursorPair(-1L, startTimestamp);
                final DatabaseWrapper db = DataModel.get().getDatabase();
                if (!recents.isSynchronized(db)) {
                    LogUtil.i(TAG, "SyncMessagesAction: Changed messages after sync; "
                            + "scheduling an incremental sync now.");

                    // Just add a new batch for recent messages
                    final SyncMessagesAction nextBatch = new SyncMessagesAction(startTimestamp, now, 0,
                            startTimestamp);
                    syncManager.startSyncBatch(now);
                    requestBackgroundWork(nextBatch);
                    // After partial sync verify sync state
                } else if (lowerBoundTimeMillis >= 0 && !olders.isSynchronized(db)) {
                    // Add a batch going back to start of time
                    LogUtil.w(TAG, "SyncMessagesAction: Changed messages before sync batch; "
                            + "scheduling a full sync now.");

                    final SyncMessagesAction nextBatch = new SyncMessagesAction(-1L, startTimestamp, 0,
                            startTimestamp);

                    syncManager.startSyncBatch(startTimestamp);
                    requestBackgroundWork(nextBatch);
                } else {
                    LogUtil.i(TAG, "SyncMessagesAction: All messages now in sync");

                    // All done, in sync
                    syncManager.complete();
                }
            }
            // Either sync should be complete or we should have a follow up request
            Assert.isTrue(hasBackgroundActions() || !syncManager.isSyncing());
        }
    }

    return null;
}

From source file:com.android.development.Connectivity.java

private void onStartScanCycle() {
    if (mScanCur == -1) {
        try {//from   ww  w . jav  a  2  s  .c o  m
            mScanCur = Long.parseLong(mScanCyclesEdit.getText().toString());
            mScanCycles = mScanCur;
        } catch (Exception e) {
        }
        ;
        if (mScanCur <= 0) {
            mScanCur = -1;
            mScanCycles = SCAN_CYCLES;
            return;
        }
    }
    if (mScanCur > 0) {
        registerReceiver(mScanRecv, mIntentFilter);
        mScanButton.setText(PROGRESS_SCAN);
        mScanResults.setVisibility(View.INVISIBLE);
        if (mScanDisconnect.isChecked())
            mWm.disconnect();
        mTotalScanTime = 0;
        mTotalScanCount = 0;
        Log.d(TAG, "Scan: START " + mScanCur);
        mStartTime = SystemClock.elapsedRealtime();
        mWm.startScan();
    } else {
        // Show results
        mScanResults.setText("Average Scan Time = " + Long.toString(mTotalScanTime / mScanCycles)
                + " ms ; Average Scan Amount = " + Long.toString(mTotalScanCount / mScanCycles));
        mScanResults.setVisibility(View.VISIBLE);
        mScanButton.setText(START_SCAN);
        mScanCur = -1;
        mScanCyclesEdit.setText(Long.toString(mScanCycles));
        if (mScanDisconnect.isChecked())
            mWm.reassociate();
    }
}

From source file:com.suning.mobile.ebuy.lottery.network.util.Caller.java

/**
 * //from  www .  j  ava  2  s  .  c  o m
 * @Description: handleMessage
 * @param m
 * @Author:12072565 
 * @Date 2013-5-6
 * @return void
 */
private void handleMessage(Message m) {
    if (m.what == 2) {
        timeSecond = SystemClock.elapsedRealtime();
        updateDate(Math.abs(timeSecond - timeFirst));
        mHandler.sendMessageDelayed(Message.obtain(mHandler, 2), 1000);
    }
}

From source file:com.guardtrax.ui.screens.HomeScreen.java

public void onCreate(Bundle savedInstanceState) {
    ctx = this.getApplicationContext();

    super.onCreate(savedInstanceState);

    //restore saved instances if necessary
    if (savedInstanceState != null) {
        Toast.makeText(HomeScreen.this, savedInstanceState.getString("message"), Toast.LENGTH_LONG).show();

        GTConstants.darfileName = savedInstanceState.getString("darfileName");
        GTConstants.tarfileName = savedInstanceState.getString("tarfileName");
        GTConstants.trpfilename = savedInstanceState.getString("trpfilename");
        GTConstants.srpfileName = savedInstanceState.getString("srpfileName");
        Utility.setcurrentState(savedInstanceState.getString("currentState"));
        Utility.setsessionStart(savedInstanceState.getString("getsessionStart"));
        selectedCode = savedInstanceState.getString("selectedCode");
        lunchTime = savedInstanceState.getString("lunchTime");
        breakTime = savedInstanceState.getString("breakTime");
        signaturefileName = savedInstanceState.getString("signaturefileName");
        GTConstants.tourName = savedInstanceState.getString("tourName");
        tourTime = savedInstanceState.getString("tourTime");
        tourEnd = savedInstanceState.getLong("tourEnd");
        lunchoutLocation = savedInstanceState.getInt("lunchoutLocation");
        breakoutLocation = savedInstanceState.getInt("breakoutLocation");
        touritemNumber = savedInstanceState.getInt("touritemNumber");
        chekUpdate = savedInstanceState.getBoolean("chekUpdate");
        GTConstants.sendData = savedInstanceState.getBoolean("send_data");
        GTConstants.isTour = savedInstanceState.getBoolean("isTour");
        GTConstants.isGeoFence = savedInstanceState.getBoolean("isGeoFence");
    } else {/* www.  j  ava  2 s  .  c  o  m*/
        //set the current state
        Utility.setcurrentState(GTConstants.offShift);

        //set the default startup code to start shift
        selectedCode = "start_shift";
    }

    /*
    //Determine screen size
     if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_LARGE) {     
         Toast.makeText(this, "Large screen",Toast.LENGTH_LONG).show();
     }
     else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL) {     
         Toast.makeText(this, "Normal sized screen" , Toast.LENGTH_LONG).show();
     } 
     else if ((getResources().getConfiguration().screenLayout &      Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL) {     
         Toast.makeText(this, "Small sized screen" , Toast.LENGTH_LONG).show();
     }
     else {
         Toast.makeText(this, "Screen size is neither large, normal or small" , Toast.LENGTH_LONG).show();
     }
             
      //initialize receiver to monitor for screen on / off
    /*
      IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
      filter.addAction(Intent.ACTION_SCREEN_OFF);
      BroadcastReceiver mReceiver = new ScreenReceiver();
      registerReceiver(mReceiver, filter);
      */

    setContentView(R.layout.homescreen);

    //Create object to call the Database class
    myDatabase = new GuardTraxDB(this);
    preferenceDB = new PreferenceDB(this);
    ftpdatabase = new ftpDataBase(this);
    gtDB = new GTParams(this);
    aDB = new accountsDB(this);
    trafficDB = new trafficDataBase(this);
    tourDB = new tourDataBase(this);

    //check for updates
    if (chekUpdate) {
        //reset the preference value
        chekUpdate = false;

        //check for application updates
        checkUpdate();
    }

    //initialize the message timer
    //initializeOnModeTimerEvent();

    //get the version number and set it in constants
    String version_num = "";

    PackageManager manager = this.getPackageManager();
    try {
        PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
        version_num = info.versionName.toString();

    } catch (NameNotFoundException e) {
        version_num = "0.00.00";
    }
    GTConstants.version = version_num;

    //final TextView version = (TextView) findViewById(R.id.textVersion);
    //version.setText(version_num);

    //set up the animation
    animation.setDuration(500); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(Animation.INFINITE); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

    buttonClick.setDuration(50); // duration - half a second
    buttonClick.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    buttonClick.setRepeatCount(1); // Repeat animation once
    buttonClick.setRepeatMode(Animation.REVERSE); // Reverse animation at the end so the button will fade back in

    textWarning = (TextView) findViewById(R.id.txtWarning);
    textWarning.setWidth(500);
    textWarning.setGravity(Gravity.CENTER);

    //allow the text to be clicked if necessary 
    textWarning.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (GTConstants.isTour && GTConstants.tourName.length() > 1)
                displaytourInfo();
        }
    });

    //goto scan page button
    btn_scan_screen = (Button) findViewById(R.id.btn_goto_scan);

    btn_scan_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_scan_screen.startAnimation(buttonClick);

            //Utility.showScan(HomeScreen.this);
            scan_click(false);
        }
    });

    //goto report page button
    btn_report_screen = (Button) findViewById(R.id.btn_goto_report);
    btn_report_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_report_screen.startAnimation(buttonClick);

            report_click();
        }
    });

    //goto dial page button
    btn_dial_screen = (Button) findViewById(R.id.btn_goto_dial);
    btn_dial_screen.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_dial_screen.startAnimation(buttonClick);

            dial_click();
        }
    });

    //microphone button
    btn_mic = (Button) findViewById(R.id.btn_mic);
    btn_mic.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_mic.startAnimation(buttonClick);

            voice_click();
        }

    });

    //camera button
    btn_camera = (Button) findViewById(R.id.btn_camera);
    btn_camera.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_camera.startAnimation(buttonClick);

            camera_click();
        }
    });

    //video button
    btn_video = (Button) findViewById(R.id.btn_video);
    btn_video.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            btn_video.startAnimation(buttonClick);

            video_click();
        }

    });

    // Register a callback to be invoked when this view is clicked. If this view is not clickable, it becomes clickable.
    btn_send = (Button) findViewById(R.id.btn_Send);
    btn_send.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            //prevent multiple fast clicking
            if (SystemClock.elapsedRealtime() - mLastClickTime < 2000)
                return;

            mLastClickTime = SystemClock.elapsedRealtime();

            incidentcodeSent = true;

            btn_send.startAnimation(buttonClick);

            //if start shift has not been sent then the device is in do not send data mode.  Warn the user 
            if (Utility.getcurrentState().equals(GTConstants.offShift) && !selectedCode.equals("start_shift")) {
                show_alert_title = "Error";
                show_alert_message = "You must start your shift!";
                showAlert(show_alert_title, show_alert_message, true);

                //set spinner back to start shift
                spinner.setSelection(0);
            } else {
                if (Utility.deviceRegistered()) {
                    show_alert_title = "Success";
                    show_alert_message = "Action success";
                } else {
                    show_alert_title = "Warning";
                    show_alert_message = "You are NOT registered!";

                    showAlert(show_alert_title, show_alert_message, true);
                }

                if (selectedCode.equals("start_shift")) {
                    //if shift already started
                    if (Utility.getcurrentState().equals(GTConstants.onShift)) {
                        show_alert_title = "Warning";
                        show_alert_message = "You must end shift!";

                        showAlert(show_alert_title, show_alert_message, true);

                        //set spinner back to all clear
                        spinner.setSelection(2);
                    } else {
                        ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                (ViewGroup) findViewById(R.id.toast_layout_root));

                        pdialog = ProgressDialog.show(HomeScreen.this, "Please wait", "Starting shift ...",
                                true);

                        //set the current state
                        Utility.setcurrentState(GTConstants.onShift);
                        setuserBanner();

                        //wait for start shift actions to complete (or timeout occurs) before dismissing wait dialog
                        new CountDownTimer(5000, 1000) {
                            @Override
                            public void onTick(long millisUntilFinished) {
                                if (start_shift_wait)
                                    pdialog.dismiss();
                            }

                            @Override
                            public void onFinish() {
                                if (!(pdialog == null))
                                    pdialog.dismiss();
                            }
                        }.start();

                        //create dar file
                        try {
                            //create the dar file name
                            GTConstants.darfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                    + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".dar";

                            //write the version to the dar file
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.darfileName,
                                    "Version;" + GTConstants.version + "\r\n", false);

                            //write the start shift event to the dar file
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.darfileName,
                                    "Start shift;" + GTConstants.currentBatteryPercent + ";"
                                            + Utility.getLocalTime() + ";" + Utility.getLocalDate() + "\r\n",
                                    true);

                            //create the tar file name if module installed
                            if (GTConstants.isTimeandAttendance) {
                                GTConstants.tarfileName = GTConstants.LICENSE_ID.substring(7) + "_"
                                        + Utility.getUTCDate() + "_" + Utility.getUTCTime() + ".tar";

                                //write the start shift event to the tar file
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                        "Name;" + GTConstants.report_name + "\r\n" + "Start shift;"
                                                + Utility.getLocalTime() + ";" + Utility.getLocalDate()
                                                + "\r\n",
                                        false);
                            }

                        } catch (Exception e) {
                            Toast.makeText(HomeScreen.this, "error = " + e, Toast.LENGTH_LONG).show();
                        }

                        GTConstants.sendData = true;

                        //if not time and attendance then send start shift event now, otherwise wait till after location scan
                        send_event("11");

                        //set the session start time
                        SimpleDateFormat sdf = new SimpleDateFormat("MM-dd-yy HH:mm:ss");
                        Utility.setsessionStart(sdf.format(new Date()));

                        //reset the server connection flag
                        Utility.resetisConnecting();

                        //start the GPS location service
                        MainService.openLocationListener();

                        //set spinner back to all clear
                        spinner.setSelection(2);

                        setwarningText("");

                        if (GTConstants.isTimeandAttendance) {
                            show_taa_scan(true, false);
                        }
                    }

                } else if (selectedCode.equals("end_shift")) {
                    if (!Utility.getcurrentState().equals(GTConstants.onShift)
                            && GTConstants.isTimeandAttendance) {
                        show_alert_title = "Error";
                        show_alert_message = "You must end your Lunch / Break!";
                        showAlert(show_alert_title, show_alert_message, true);

                        //set spinner back to start shift
                        spinner.setSelection(2);
                    } else {
                        btn_send.setEnabled(false);
                        if (GTConstants.isTimeandAttendance) {
                            show_taa_scan(false, true);
                        } else
                            endshiftCode();
                    }
                } else {
                    if (Utility.isselectionValid(HomeScreen.this, selectedCode)) {
                        //if time and attendance then write to file
                        if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)
                                || selectedCode.equalsIgnoreCase(GTConstants.lunchout)
                                || selectedCode.equalsIgnoreCase(GTConstants.startbreak)
                                || selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                            if (GTConstants.isTimeandAttendance)
                                Utility.write_to_file(HomeScreen.this,
                                        GTConstants.dardestinationFolder + GTConstants.tarfileName,
                                        spinner.getSelectedItem().toString() + ";" + Utility.getLocalTime()
                                                + ";" + Utility.getLocalDate() + "\r\n",
                                        true);

                            if (selectedCode.equalsIgnoreCase(GTConstants.lunchin)) {
                                Utility.setcurrentState(GTConstants.onLunch);
                                Utility.setlunchStart(true);
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.startbreak)) {
                                Utility.setcurrentState(GTConstants.onBreak);
                                Utility.setbreakStart(true);
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.lunchout)) {
                                Utility.setcurrentState(GTConstants.onShift);
                                lunchTime = Utility.gettimeDiff(Utility.getlunchStart(),
                                        Utility.getLocalDateTime());
                                setuserBanner();
                            }

                            if (selectedCode.equalsIgnoreCase(GTConstants.endbreak)) {
                                Utility.setcurrentState(GTConstants.onShift);
                                breakTime = Utility.gettimeDiff(Utility.getbreakStart(),
                                        Utility.getLocalDateTime());
                                setuserBanner();
                            }
                        }

                        ToastMessage.displayToastFromResource(HomeScreen.this, 5, Gravity.CENTER,
                                (ViewGroup) findViewById(R.id.toast_layout_root));

                        //save the event description as may be needed for incident report
                        incidentDescription = spinner.getSelectedItem().toString();

                        //write to dar
                        Utility.write_to_file(HomeScreen.this,
                                GTConstants.dardestinationFolder + GTConstants.darfileName,
                                "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                        + Utility.getLocalDate() + "\r\n",
                                true);

                        //write to srp
                        if (GTConstants.srpfileName.length() > 1)
                            Utility.write_to_file(HomeScreen.this,
                                    GTConstants.dardestinationFolder + GTConstants.srpfileName,
                                    "Event; " + incidentDescription + ";" + Utility.getLocalTime() + ";"
                                            + Utility.getLocalDate() + "\r\n",
                                    true);

                        //send the data
                        send_event(selectedCode);

                        //ask if user wants to create an incident report.  If the last character is a space, that indicates not to ask for report
                        if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                && !trafficIncident)
                            showYesNoAlert("Report", "Create an Incident Report?", incidentreportScreen);
                        if (!(incidentDescription.charAt(incidentDescription.length() - 1) == ' ')
                                && trafficIncident)
                            showYesNoAlert("Report", "Create a Traffic Violation?", incidentreportScreen);

                        //if last two characters are spaces then ask to write a note
                        if (incidentDescription.charAt(incidentDescription.length() - 1) == ' '
                                && incidentDescription.charAt(incidentDescription.length() - 2) == ' ')
                            showYesNoAlert("Report", "Create a Note?", createNote);

                    }

                    //set spinner back to required state
                    if (selectedCode.equalsIgnoreCase(GTConstants.lunchin))
                        spinner.setSelection(lunchoutLocation);
                    else if (selectedCode.equalsIgnoreCase(GTConstants.startbreak))
                        spinner.setSelection(breakoutLocation);
                    else
                        spinner.setSelection(2);

                }
            }
        }

    });

    //Finds a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle).
    spinner = (Spinner) findViewById(R.id.spinner_list);

    //method initialize the spinner action
    initializeSpinnerControl();

    if (GTConstants.service_intent == null) {
        //Condition to check whether the Database exist and if so load data into constants
        try {
            if (preferenceDB.checkDataBase()) {
                preferenceDB.open();

                Cursor cursor = preferenceDB.getRecordByRowID("1");

                preferenceDB.close();

                if (cursor == null)
                    loadPreferenceDataBase();
                else {
                    saveInConstants(cursor);
                    cursor.close();
                }
                syncDB();
                syncFTP();
                syncftpUpload();
            } else {
                preferenceDB.open();
                preferenceDB.close();
                //Toast.makeText(HomeScreen.this, "Path = " + preferenceDB.get_path(), Toast.LENGTH_LONG).show();
                //Toast.makeText(HomeScreen.this, "No database found", Toast.LENGTH_LONG).show();

                loadPreferenceDataBase();

                syncDB();
                syncFTP();
                syncftpUpload();
            }
        } catch (Exception e) {
            preferenceDB.createDataBase();
            loadPreferenceDataBase();
            Toast.makeText(HomeScreen.this, "Creating database", Toast.LENGTH_LONG).show();
        }

        //setup the auxiliary databases
        if (!aDB.checkDataBase()) {
            aDB.open();
            aDB.close();
        }

        if (!ftpdatabase.checkDataBase()) {
            ftpdatabase.open();
            ftpdatabase.close();
        }

        if (!gtDB.checkDataBase()) {
            gtDB.open();
            gtDB.close();
        }

        if (!trafficDB.checkDataBase()) {
            trafficDB.open();
            trafficDB.close();
        }

        if (!tourDB.checkDataBase()) {
            tourDB.open();
            tourDB.close();
        }

        //get the parameters from the parameter database
        loadGTParams();

        //this code starts the main service running which contains all the event timers
        if (Utility.deviceRegistered()) {
            //this is the application started event - sent once when application starts up
            if (savedInstanceState == null)
                send_event("PU");

            initService();
        }
    }

    //if device not registered than go straight to scan screen
    if (!Utility.deviceRegistered()) {
        newRegistration = true;
        //send_data = true;
        scan_click(false);
    }

    //setup the user banner
    setuserBanner();

    //set the warning text
    setwarningText("");

}

From source file:edu.missouri.bas.service.SensorService.java

public void startSound() {

    Intent scheduleTriggerSound = new Intent(SensorService.ACTION_TRIGGER_SOUND);
    Intent scheduleTriggerSound2 = new Intent(SensorService.ACTION_TRIGGER_SOUND2);
    triggerSound = PendingIntent.getBroadcast(serviceContext, 0, scheduleTriggerSound, 0);
    triggerSound2 = PendingIntent.getBroadcast(serviceContext, 0, scheduleTriggerSound2, 0);
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, triggerSound);
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000 * 20,
            triggerSound2);//  ww  w  .  j a v a  2 s.  co  m

}

From source file:com.onesignal.OneSignal.java

static void onAppFocus() {
    foreground = true;/*from w w w.  ja  va2  s . c o  m*/
    lastTrackedTime = SystemClock.elapsedRealtime();

    startRegistrationOrOnSession();

    if (trackGooglePurchase != null)
        trackGooglePurchase.trackIAP();
}