Example usage for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

List of usage examples for android.app AlarmManager ELAPSED_REALTIME_WAKEUP

Introduction

In this page you can find the example usage for android.app AlarmManager ELAPSED_REALTIME_WAKEUP.

Prototype

int ELAPSED_REALTIME_WAKEUP

To view the source code for android.app AlarmManager ELAPSED_REALTIME_WAKEUP.

Click Source Link

Document

Alarm time in android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime() (time since boot, including sleep), which will wake up the device when it goes off.

Usage

From source file:com.t2.compassionMeditation.Graphs1Activity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView
    setContentView(R.layout.graphs_activity_layout);
    mInstance = this;

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {/*from   www.j  a  v a  2s  . co m*/
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    String userId = SharedPref.getString(this, "SelectedUser", "");
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);

    }

    mBioDataProcessor.initialize(mDataOutHandler);

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // Set up UI elements
    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    mPauseButton = (Button) findViewById(R.id.buttonPause);
    mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure);
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText);

    // Don't actually show skin conductance meter unless we get samples
    ImageView image = (ImageView) findViewById(R.id.imageView1);
    image.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        image.setVisibility(View.VISIBLE);
    } else {
        image.setVisibility(View.INVISIBLE);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    try {
        currentMindsetData = new MindsetData(this);
    } catch (Exception e1) {
        Log.e(TAG, "Exception creating MindsetData: " + e1.toString());
        e1.printStackTrace();
    }

    // Establish nodes for BSPAN

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    // First create GraphBioParameters for each of the EEG static params (ie mindset)
    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate
    //       String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // Since These are static nodes (Non-spine) we have to manually put them in the active node list
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    final String sessionName;

    // Check to see if we were requested to play back a previous session
    try {
        Bundle bundle = getIntent().getExtras();

        if (bundle != null) {
            sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME);

            AlertDialog.Builder alert = new AlertDialog.Builder(this);
            alert.setTitle("Replay Session " + sessionName + "?");
            alert.setMessage("Make sure to turn off all Bluetooth Sensors!");

            alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {

                    try {
                        mDataOutHandler.logNote("Replaying data from session " + sessionName);
                    } catch (DataOutHandlerException e) {
                        Log.e(TAG, e.toString());
                        e.printStackTrace();
                    }

                    replaySessionData(sessionName);
                    AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance);
                    alert1.setTitle("INFO");
                    alert1.setMessage("Replay of session complete!");
                    alert1.show();

                }
            });
            alert.show();
        }

    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0,
                new Intent(Graphs1Activity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

    //testFIRFilter();

    //       testHR();

}

From source file:de.ub0r.android.websms.WebSMSReceiver.java

/**
 * Schedules resend of a message.//  w ww.j  a  v  a2  s . c o m
 *
 * @param context context
 * @param specs   {@link de.ub0r.android.websms.connector.common.ConnectorSpec}
 * @param command {@link de.ub0r.android.websms.connector.common.ConnectorCommand}
 */
private static void scheduleMessageResend(final Context context, final ConnectorSpec specs,
        final ConnectorCommand command) {

    long msgId = command.getMsgId();

    final Intent resendIntent = new Intent(Connector.ACTION_RESEND);
    command.setToIntent(resendIntent);
    specs.setToIntent(resendIntent);

    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + RESEND_DELAY_MS,
            PendingIntent.getBroadcast(context, (int) msgId, resendIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.example.cody.tapwater.activities.MainActivity.java

@Override
public void onResume() {
    super.onResume();
    System.out.println("Alarm manager setup");
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
    String prompts = prefs.getString("prompts", "5");
    String beginStr = prefs.getString("begin_time", "");
    String endStr = prefs.getString("end_time", "");
    Calendar beginCal = Calendar.getInstance();
    Calendar endCal = Calendar.getInstance();
    try {//from   w  ww  . j av  a 2s . co  m
        beginCal.setTime(sdf.parse(beginStr));
        endCal.setTime(sdf.parse(endStr));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long interval = notificationIntervalCalculation(Integer.valueOf(prompts), beginCal, endCal);
    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    Intent i = new Intent(context, NotificationService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, 0);
    am.cancel(pi);

    // by my own convention, minutes <= 0 means notifications are disabled
    if (interval > 0) {
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + interval,
                interval, pi);
    }
}

From source file:org.vshgap.android.NotificationsController.java

private void scheduleNotificationDelay(boolean onlineReason) {
    try {//ww w . ja  va 2s.c  om
        FileLog.e("tmessages", "delay notification start, onlineReason = " + onlineReason);
        AlarmManager alarm = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
        PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0,
                new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        if (onlineReason) {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
        } else {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pintent);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:org.sipdroid.sipua.ui.Receiver.java

public static void alarm(int renew_time, Class<?> cls) {
    if (!Sipdroid.release)
        Log.i("SipUA:", "alarm " + renew_time);
    Intent intent = new Intent(mContext, cls);
    PendingIntent sender = PendingIntent.getBroadcast(mContext, 0, intent, 0);
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    am.cancel(sender);/* ww w . ja  v  a2s . c  o m*/
    if (renew_time > 0)
        am.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + renew_time * 1000, sender);
}

From source file:com.koma.music.service.MusicService.java

private void scheduleDelayedShutdown() {
    LogUtils.d(TAG, "Scheduling shutdown in " + MusicServiceConstants.IDLE_DELAY + " ms");
    if (!mReadGranted) {
        return;//from  w  w  w  .j a va 2 s  .c  om
    }
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + MusicServiceConstants.IDLE_DELAY, mShutdownIntent);
    mShutdownScheduled = true;
}

From source file:com.umaps.gpslogger.GpsLoggingService.java

private void SetAlarmForNextPoint() {
    Log.d(TAG, "Set alarm for " + AppSettings.getMinimumSeconds() + " seconds");

    Intent i = new Intent(this, GpsLoggingService.class);
    i.putExtra(IntentConstants.GET_NEXT_POINT, true);
    PendingIntent pi = PendingIntent.getService(this, 0, i, 0);
    nextPointAlarmManager.cancel(pi);// w  w w  .j a  va 2  s.  co m

    nextPointAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + AppSettings.getMinimumSeconds() * 1000, pi);
}

From source file:com.av.remusic.service.MediaService.java

private void scheduleDelayedShutdown() {
    if (D)//from w w w  .  jav  a 2  s  .  c om
        Log.v(TAG, "Scheduling shutdown in " + IDLE_DELAY + " ms");
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + IDLE_DELAY,
            mShutdownIntent);
    mShutdownScheduled = true;
}

From source file:com.t2.compassionMeditation.MeditationActivity.java

/** Called when the activity is first created. */
@Override/*from  ww w  .  j ava 2s . c o  m*/
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()");

    mInstance = this;
    mRateOfChange = new RateOfChange(mRateOfChangeSize);

    mIntroFade = 255;

    // We don't want the screen to timeout in this activity
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView

    setContentView(R.layout.buddah_activity_layout);

    sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    currentMindsetData = new MindsetData(this);
    mSaveRawWave = SharedPref.getBoolean(this, BioZenConstants.PREF_SAVE_RAW_WAVE,
            BioZenConstants.PREF_SAVE_RAW_WAVE_DEFAULT);

    mShowAGain = SharedPref.getBoolean(this, BioZenConstants.PREF_SHOW_A_GAIN,
            BioZenConstants.PREF_SHOW_A_GAIN_DEFAULT);

    mAllowComments = SharedPref.getBoolean(this, BioZenConstants.PREF_COMMENTS,
            BioZenConstants.PREF_COMMENTS_DEFAULT);

    mShowForeground = SharedPref.getBoolean(this, "show_lotus", true);
    mShowToast = SharedPref.getBoolean(this, "show_toast", true);

    mAudioTrackResourceName = SharedPref.getString(this, "audio_track", "None");
    mBaseImageResourceName = SharedPref.getString(this, "background_images", "Sunset");

    mBioHarnessParameters = getResources().getStringArray(R.array.bioharness_parameters_array);

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    String s = SharedPref.getString(this, BioZenConstants.PREF_SESSION_LENGTH, "10");
    mSecondsRemaining = Integer.parseInt(s) * 60;
    mSecondsTotal = mSecondsRemaining;

    s = SharedPref.getString(this, BioZenConstants.PREF_ALPHA_GAIN, "5");
    mAlphaGain = Float.parseFloat(s);

    mMovingAverage = new TMovingAverageFilter(mMovingAverageSize);
    mMovingAverageROC = new TMovingAverageFilter(mMovingAverageSizeROC);

    View v1 = findViewById(R.id.buddahView);
    v1.setOnTouchListener(this);

    Resources resources = this.getResources();
    AssetManager assetManager = resources.getAssets();

    // Set up member variables to UI Elements
    mTextInfoView = (TextView) findViewById(R.id.textViewInfo);
    mTextBioHarnessView = (TextView) findViewById(R.id.textViewBioHarness);
    mCountdownTextView = (TextView) findViewById(R.id.countdownTextView);
    mCountdownImageView = (ImageView) findViewById(R.id.imageViewCountdown);

    mPauseButton = (ImageButton) findViewById(R.id.buttonPause);
    mSignalImage = (ImageView) findViewById(R.id.imageView1);
    mTextViewInstructions = (TextView) findViewById(R.id.textViewInstructions);

    // Note that the seek bar is a debug thing - used only to set the
    // alpha of the buddah image manually for visual testing
    mSeekBar = (SeekBar) findViewById(R.id.seekBar1);
    mSeekBar.setOnSeekBarChangeListener(this);

    // Scale such that values to the right of center are scaled 1 - 10
    // and values to the left of center are scaled 0 = .99999
    if (mAlphaGain > 1.0) {
        mSeekBar.setProgress(50 + (int) (mAlphaGain * 5));
    } else {
        int i = (int) (mAlphaGain * 50);
        mSeekBar.setProgress(i);
    }
    //      mSeekBar.setProgress((int) mAlphaGain * 10);      

    // Controls start as invisible, need to touch screen to activate them
    mCountdownTextView.setVisibility(View.INVISIBLE);
    mCountdownImageView.setVisibility(View.INVISIBLE);
    mTextInfoView.setVisibility(View.INVISIBLE);
    mTextBioHarnessView.setVisibility(View.INVISIBLE);
    mPauseButton.setVisibility(View.INVISIBLE);
    mPauseButton.setVisibility(View.VISIBLE);
    mSeekBar.setVisibility(View.INVISIBLE);

    mBackgroundImage = (ImageView) findViewById(R.id.buddahView);
    mForegroundImage = (ImageView) findViewById(R.id.lotusView);
    mBaseImage = (ImageView) findViewById(R.id.backgroundView);

    if (!mShowForeground) {
        mForegroundImage.setVisibility(View.INVISIBLE);
    }

    int resource = 0;
    if (mBaseImageResourceName.equalsIgnoreCase("Buddah")) {
        mBackgroundImage.setImageResource(R.drawable.buddha);
        mForegroundImage.setImageResource(R.drawable.lotus_flower);
        mBaseImage.setImageResource(R.drawable.none_bg);
    } else if (mBaseImageResourceName.equalsIgnoreCase("Bob")) {
        mBackgroundImage.setImageResource(R.drawable.bigbob);
        mForegroundImage.setImageResource(R.drawable.red_nose);
        mBaseImage.setImageResource(R.drawable.none_bg);
    } else if (mBaseImageResourceName.equalsIgnoreCase("Sunset")) {
        mBackgroundImage.setImageResource(R.drawable.eeg_layer);
        mForegroundImage.setImageResource(R.drawable.breathing_rate);
        mBaseImage.setImageResource(R.drawable.meditation_bg);
    }

    // Initialize SPINE by passing the fileName with the configuration properties
    try {
        mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources);
    } catch (InstantiationException e) {
        Log.e(TAG, "Exception creating SPINE manager: " + e.toString());
        e.printStackTrace();
    }

    // Since Mindset is a static node we have to manually put it in the active node list
    // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor
    Node mindsetNode = null;
    mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET));
    mManager.getActiveNodes().add(mindsetNode);

    Node zepherNode = null;
    zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR));
    mManager.getActiveNodes().add(zepherNode);

    // The arduino node is programmed to look like a static Spine node
    // Note that currently we don't have  to turn it on or off - it's always streaming
    // Since Spine (in this case) is a static node we have to manually put it in the active node list
    // Since the 
    final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001
    mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE));
    mManager.getActiveNodes().add(mSpineNode);

    // Create a broadcast receiver. Note that this is used ONLY for command messages from the service
    // All data from the service goes through the mail SPINE mechanism (received(Data data)).
    // See public void received(Data data)
    this.mCommandReceiver = new SpineReceiver(this);

    try {
        PackageManager packageManager = this.getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(this.getPackageName(), 0);
        mApplicationVersion = info.versionName;
        Log.i(TAG, "BioZen Application Version: " + mApplicationVersion + ", Activity Version: "
                + mActivityVersion);
    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    // First create GraphBioParameters for each of the ECG static params (ie mindset)      
    int itemId = 0;
    eegPos = itemId; // eeg always comes first
    mBioParameters.clear();

    for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation
        GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true);
        param.isShimmer = false;
        mBioParameters.add(param);
    }

    // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, HR, Skin Temp, Resp Rate
    String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names);

    for (String paramName : paramNamesStringArray) {
        if (paramName.equalsIgnoreCase("not assigned"))
            continue;

        if (paramName.equalsIgnoreCase("EEG"))
            continue;

        GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true);

        if (paramName.equalsIgnoreCase("gsr")) {
            gsrPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("emg")) {
            emgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("ecg")) {
            ecgPos = itemId;
            param.isShimmer = true;
            param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR;
            param.shimmerNode = getShimmerNode();
        }

        if (paramName.equalsIgnoreCase("heart rate")) {
            heartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("resp rate")) {
            respRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("skin temp")) {
            skinTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Airflow")) {
            eHealthAirFlowPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Temp")) {
            eHealthTempPos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth SpO2")) {
            eHealthSpO2Pos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth Heartrate")) {
            eHealthHeartRatePos = itemId;
            param.isShimmer = false;
        }

        if (paramName.equalsIgnoreCase("EHealth GSR")) {
            eHealthGSRPos = itemId;
            param.isShimmer = false;
        }

        itemId++;
        mBioParameters.add(param);
    }

    // The session start time will be used as session id
    // Note this also sets session start time
    // **** This session ID will be prepended to all JSON data stored
    //      in the external database until it's changed (by the start
    //      of a new session.
    Calendar cal = Calendar.getInstance();
    SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis());

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US);
    String sessionDate = sdf.format(new Date());
    long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0);

    mUserId = SharedPref.getString(this, "SelectedUser", "");

    // Now get the database object associated with this user

    try {
        mBioUserDao = getHelper().getBioUserDao();
        mBioSessionDao = getHelper().getBioSessionDao();

        QueryBuilder<BioUser, Integer> builder = mBioUserDao.queryBuilder();
        builder.where().eq(BioUser.NAME_FIELD_NAME, mUserId);
        builder.limit(1);
        //         builder.orderBy(ClickCount.DATE_FIELD_NAME, false).limit(30);
        List<BioUser> list = mBioUserDao.query(builder.prepare());

        if (list.size() == 1) {
            mCurrentBioUser = list.get(0);
        } else if (list.size() == 0) {
            try {
                mCurrentBioUser = new BioUser(mUserId, System.currentTimeMillis());
                mBioUserDao.create(mCurrentBioUser);
            } catch (SQLException e1) {
                Log.e(TAG, "Error creating user " + mUserId, e1);
            }
        } else {
            Log.e(TAG, "General Database error" + mUserId);
        }

    } catch (SQLException e) {
        Log.e(TAG, "Can't find user: " + mUserId, e);

    }

    mSignalImage.setImageResource(R.drawable.signal_bars0);

    // Check to see of there a device configured for EEG, if so then show the skin conductance meter
    String tmp = SharedPref.getString(this, "EEG", null);

    if (tmp != null) {
        mSignalImage.setVisibility(View.VISIBLE);
        mTextViewInstructions.setVisibility(View.VISIBLE);

    } else {
        mSignalImage.setVisibility(View.INVISIBLE);
        mTextViewInstructions.setVisibility(View.INVISIBLE);
    }

    mDataOutHandler = new DataOutHandler(this, mUserId, sessionDate, mAppId,
            DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId);

    if (mDatabaseEnabled) {
        TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
        String myNumber = telephonyManager.getLine1Number();

        String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name",
                getString(R.string.database_uri));
        //            remoteDatabaseUri += myNumber; 

        Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove
        try {
            mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName,
                    remoteDatabaseUri);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }
        mDataOutHandler.setRequiresAuthentication(false);
    }

    mBioDataProcessor.initialize(mDataOutHandler);

    mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true);
    mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false);
    mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false);

    mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false);

    if (mAntHrmEnabled) {
        mHeartRateSource = HEARTRATE_ANT;
    } else {
        mHeartRateSource = HEARTRATE_ZEPHYR;
    }

    if (mLoggingEnabled) {
        mDataOutHandler.enableLogging(this);
    }

    if (mLogCatEnabled) {
        mDataOutHandler.enableLogCat();
    }

    // Log the version
    try {
        PackageManager packageManager = getPackageManager();
        PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0);
        mApplicationVersion = info.versionName;
        String versionString = mAppId + " application version: " + mApplicationVersion;

        DataOutPacket packet = new DataOutPacket();
        packet.add(DataOutHandlerTags.version, versionString);
        try {
            mDataOutHandler.handleDataOut(packet);
        } catch (DataOutHandlerException e) {
            Log.e(TAG, e.toString());
            e.printStackTrace();
        }

    } catch (NameNotFoundException e) {
        Log.e(TAG, e.toString());
    }

    if (mInternalSensorMonitoring) {
        // IntentSender Launches our service scheduled with with the alarm manager 
        mBigBrotherService = PendingIntent.getService(MeditationActivity.this, 0,
                new Intent(MeditationActivity.this, BigBrotherService.class), 0);

        long firstTime = SystemClock.elapsedRealtime();
        // Schedule the alarm!
        AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000,
                mBigBrotherService);

        // Tell the user about what we did.
        Toast.makeText(MeditationActivity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show();

    }

}

From source file:org.wso2.cdm.agent.AuthenticationActivity.java

private void startLocalNotification(Float interval) {
    long firstTime = SystemClock.elapsedRealtime();
    firstTime += 1 * 1000;/*ww  w. j a  v a2 s .co m*/

    Intent downloader = new Intent(context, AlarmReceiver.class);
    PendingIntent recurringDownload = PendingIntent.getBroadcast(context, 0, downloader,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Float seconds = interval;
    if (interval < 1.0) {

        alarms.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, seconds.intValue(),
                recurringDownload);
    } else {
        alarms.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, seconds.intValue(),
                recurringDownload);
    }

}