Example usage for android.app AlarmManager setRepeating

List of usage examples for android.app AlarmManager setRepeating

Introduction

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

Prototype

public void setRepeating(@AlarmType int type, long triggerAtMillis, long intervalMillis,
        PendingIntent operation) 

Source Link

Document

Schedule a repeating alarm.

Usage

From source file:org.ohmage.reminders.types.location.LocTrigService.java

private void setKeepAliveAlarm(Context context) {
    Intent i = new Intent(ACTION_ALRM_SRV_KEEP_ALIVE).setPackage(context.getPackageName());

    //set the alarm if not already existing
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE);

    AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pi != null) {
        alarmMan.cancel(pi);/*from   w  w  w .  jav a2 s  . co  m*/
        pi.cancel();
    }

    pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

    alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + SERV_KEEP_ALIVE_TIME, SERV_KEEP_ALIVE_TIME, pi);
}

From source file:org.ohmage.triggers.types.location.LocTrigService.java

private void setKeepAliveAlarm() {
    Intent i = new Intent(ACTION_ALRM_SRV_KEEP_ALIVE);

    //set the alarm if not already existing
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_NO_CREATE);

    AlarmManager alarmMan = (AlarmManager) getSystemService(ALARM_SERVICE);
    if (pi != null) {
        alarmMan.cancel(pi);//  www.j ava 2  s.c  o m
        pi.cancel();
    }

    pi = PendingIntent.getBroadcast(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

    alarmMan.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + SERV_KEEP_ALIVE_TIME, SERV_KEEP_ALIVE_TIME, pi);
}

From source file:org.nerdcircus.android.klaxon.Notifier.java

@Override
public void onReceive(Context context, Intent intent) {
    NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    AlarmManager am = (AlarmManager) context.getSystemService(Activity.ALARM_SERVICE);

    if (intent.getAction().equals(Pager.PAGE_RECEIVED)) {
        Log.d(TAG, "new page received. notifying.");

        //get subject line of page, for notification.
        Cursor cursor = context.getContentResolver().query(intent.getData(),
                new String[] { Pager.Pages._ID, Pager.Pages.SUBJECT }, null, null, null);
        cursor.moveToFirst();/*from w  ww  .jav  a2 s.c  om*/
        String page_subj = cursor.getString(cursor.getColumnIndex(Pager.Pages.SUBJECT));

        Notification n = getNotification(context, page_subj);
        n.sound = null; //no noise initially. wait for the delayed ANNOY action below.
        nm.notify(R.string.notify_page, n);

        Intent i = new Intent(Pager.ANNOY_ACTION);
        //we cant use data here, because it makes the silencing fail.
        i.putExtra("notification_text", page_subj);
        PendingIntent annoyintent = PendingIntent.getBroadcast(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);

        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);

        Log.d(TAG, "notifcation interval: " + prefs.getString("notification_interval", "unknown"));
        long repeat_interval_ms = Integer.valueOf(prefs.getString("notification_interval", "20000"))
                .longValue();
        Log.d(TAG, "notifcation interval: " + repeat_interval_ms);

        // 500 ms delay, to prevent the regular text message noise from stomping on us.
        am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 500, repeat_interval_ms,
                annoyintent);
    } else if (intent.getAction().equals(Pager.SILENCE_ACTION)) {
        Log.d(TAG, "cancelling the notification...");
        Intent i = new Intent(Pager.ANNOY_ACTION);
        PendingIntent annoyintent = PendingIntent.getBroadcast(context, 0, i,
                PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(annoyintent);
        nm.cancel(R.string.notify_page);
    } else if (intent.getAction().equals(Pager.ANNOY_ACTION)) {
        Log.e(TAG, "got annoy intent. annoying.");
        //just be annoying.
        Notification n = getNotification(context, intent.getStringExtra("notification_text"));
        nm.notify(R.string.notify_page, n);
    } else if (intent.getAction().equals("org.nerdcircus.android.klaxon.REPLY_SENT")) {
        //a reply was sent. update state in the db.
        if (Activity.RESULT_OK == getResultCode()) {
            Log.d(TAG, "reply successful. updating ack status..");
            //result was sent. update state.
            updateAckStatus(context, intent.getData(), intent.getIntExtra(Pager.EXTRA_NEW_ACK_STATUS, 0));
        } else {
            Log.e(TAG, "reply failed!!! doing nothing.");
        }
    } else {
        Log.e(TAG, "Uncaught Action:" + intent.getAction());
    }

}

From source file:com.near.chimerarevo.activities.MainActivity.java

@Override
public void onDestroy() {
    super.onDestroy();
    if (ImageLoader.getInstance().isInited()) {
        ImageLoader.getInstance().clearDiskCache();
        ImageLoader.getInstance().clearMemoryCache();
    }/*from w  w  w.  ja  va 2  s .co  m*/
    if (mHelper != null)
        mHelper.dispose();

    if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("news_search_pref", true)) {
        Intent intent = new Intent(getApplicationContext(), NewsService.class);
        PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, intent, 0);
        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

        alarm.cancel(pintent);

        long delay;
        int sel = Integer.parseInt(
                PreferenceManager.getDefaultSharedPreferences(this).getString("notification_delay_pref", "0"));

        switch (sel) {
        case 0:
            delay = AlarmManager.INTERVAL_FIFTEEN_MINUTES;
            break;
        case 1:
            delay = AlarmManager.INTERVAL_HALF_HOUR;
            break;
        case 2:
            delay = AlarmManager.INTERVAL_HOUR;
            break;
        case 3:
            delay = 2 * AlarmManager.INTERVAL_HOUR;
            break;
        case 4:
            delay = 3 * AlarmManager.INTERVAL_HOUR;
            break;
        case 5:
            delay = 6 * AlarmManager.INTERVAL_HOUR;
            break;
        case 6:
            delay = AlarmManager.INTERVAL_HALF_DAY;
            break;
        case 7:
            delay = AlarmManager.INTERVAL_DAY;
            break;
        default:
            delay = AlarmManager.INTERVAL_HOUR;
            break;
        }

        alarm.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.uptimeMillis(), delay, pintent);
    }
}

From source file:com.gpsmobitrack.gpstracker.MenuItems.SettingsPage.java

/**
 * Start the alarm service //from w  ww.  j a v a  2 s .c  o m
 * @param pos
 */
private void startAlarmService(int pos) {
    editor.putLong(AppConstants.FREQ_UPDATE_PREF, updateDurationValue[pos]);
    editor.commit();
    int updateTimeint = updateDurationValue[pos];
    AlarmManager alarm = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
    Calendar cal = Calendar.getInstance();
    Intent intent2 = new Intent(getActivity(), BackgroundService.class);
    PendingIntent pintent = PendingIntent.getService(getActivity(), 0, intent2, 0);
    if (PendingIntent.getService(getActivity(), 0, intent2, PendingIntent.FLAG_NO_CREATE) != null) {
        alarm.cancel(pintent);
    }
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), (updateTimeint * 1000 * 60), pintent);
}

From source file:com.xorcode.andtweet.AndTweetService.java

/**
 * Starts the repeating Alarm that sends the fetch Intent.
 */// www.  j a va  2  s  .  co  m
private boolean scheduleRepeatingAlarm() {
    final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    final PendingIntent pIntent = getRepeatingIntent();
    final int frequencyMs = getFetchFrequencyS();
    final long firstTime = SystemClock.elapsedRealtime() + frequencyMs;
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, frequencyMs, pIntent);
    MyLog.d(TAG, "Started repeating alarm in a " + frequencyMs + "ms rhythm.");
    return true;
}

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  w w w  .  j a v  a2  s  . c om*/
        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:org.restcomm.app.qoslib.Services.TrackingManager.java

public void startCoverageTracking() {
    bTracking = true;/*w  ww . j  a v  a2  s  . c o  m*/
    this.owner.keepAwake(true, true);
    AlarmManager alarmMgr = (AlarmManager) owner.getSystemService(Service.ALARM_SERVICE);
    Intent intent = new Intent(IntentHandler.ACTION_TRACKING_5MINUTE);
    PendingIntent alarm = PendingIntent.getBroadcast(owner, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
    alarmMgr.cancel(alarm);
    //trackingExpires = System.currentTimeMillis() + (numFiveMinutePeriods) * 5L * 60L * 1000L;

    //PreferenceManager.getDefaultSharedPreferences(owner).edit().putLong(PreferenceKeys.Miscellaneous.TRACKING_EXPIRES, trackingExpires).commit();
    long expiresTime = System.currentTimeMillis() + (durMinutes * 60 - trackingElapsed) * 1000;
    PreferenceManager.getDefaultSharedPreferences(owner).edit()
            .putLong(PreferenceKeys.Miscellaneous.ENGINEER_MODE_EXPIRES_TIME, expiresTime).commit();

    long delay = 0;
    if (durMinutes == 0) // continuous tracking
    {
        //trackingExpires = 0;
        // store a tracking expiry date of 10 million seconds from now
        //PreferenceManager.getDefaultSharedPreferences(owner).edit().putLong(PreferenceKeys.Miscellaneous.TRACKING_EXPIRES, System.currentTimeMillis()+10000000000l).commit();
        PreferenceManager.getDefaultSharedPreferences(owner).edit()
                .putLong(PreferenceKeys.Miscellaneous.ENGINEER_MODE_EXPIRES_TIME, System.currentTimeMillis())
                .commit();
    }
    LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "startTracking",
            "durationMinutes=" + durMinutes + ",covInterval=" + coverageInterval + ",SpeedInterval="
                    + speedtestInterval + ",videoInterval=" + videoInterval);

    delay = 5L * 60L * 1000L;
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000, delay, alarm);
}

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

/** Called when the activity is first created. */
@Override//from  w ww .  ja  v a2 s. 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:opensource.zeocompanion.ZeoCompanionApplication.java

private void configAlarmManagerToPrefs() {
    // setup a daily alarm if auto-emailing is enabled
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    boolean enabledAutoEmail = prefs.getBoolean("email_auto_enable", false);
    boolean enabledDatabaseReplicate = prefs.getBoolean("database_replicate_zeo", false);
    long desiredTOD = prefs.getLong("email_auto_send_time", 0); // will default to midnight
    long configuredTOD = prefs.getLong("email_auto_send_time_configured", 0); // will default to midnight

    // determine whether there is an active AlarmManager entry that we have established
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intentCheck = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
    intentCheck.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
    PendingIntent existingPi = PendingIntent.getBroadcast(this, 0, intentCheck, PendingIntent.FLAG_NO_CREATE);

    if (enabledAutoEmail || enabledDatabaseReplicate) {
        // Daily AlarmManager is needed
        if (existingPi != null && desiredTOD != configuredTOD) {
            // there is an existing AlarmManager entry, but it has the incorrect starting time-of-day;
            // so cancel it, and rebuild a new one
            Intent intent1 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent1.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi1 = PendingIntent.getBroadcast(this, 0, intent1, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pi1);//from w  w w.j  a v a 2  s .com
            pi1.cancel();
            existingPi = null;
        }
        if (existingPi == null) {
            // there is no existing AlarmManager entry, so create it
            Date dt = new Date(desiredTOD);
            Calendar calendar = Calendar.getInstance();
            calendar.set(Calendar.HOUR_OF_DAY, dt.getHours());
            calendar.set(Calendar.MINUTE, dt.getMinutes());
            calendar.set(Calendar.SECOND, dt.getSeconds());
            Intent intent2 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent2.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi2 = PendingIntent.getBroadcast(this, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
            am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                    pi2);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("email_auto_send_time_configured", desiredTOD);
            editor.commit();
        }

    } else {
        // Daily AlarmManager is not needed
        if (existingPi != null) {
            // there is an AlarmManager entry pending; need to cancel it
            Intent intent3 = new Intent(this, ZeoCompanionApplication.AlarmReceiver.class);
            intent3.setAction(ZeoCompanionApplication.ACTION_ALARMMGR_WAKEUP_RTC);
            PendingIntent pi3 = PendingIntent.getBroadcast(this, 0, intent3, PendingIntent.FLAG_CANCEL_CURRENT);
            am.cancel(pi3);
            pi3.cancel();
        }
    }
}