Example usage for android.app AlarmManager RTC_WAKEUP

List of usage examples for android.app AlarmManager RTC_WAKEUP

Introduction

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

Prototype

int RTC_WAKEUP

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

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC), which will wake up the device when it goes off.

Usage

From source file:org.ohmage.reminders.notif.Notifier.java

private static void setAlarm(Context context, String action, int mins, Bundle extras) {

    Log.v(TAG, "Notifier: Setting alarm(" + mins + ", " + action + ")");

    AlarmManager alarmMan = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent i = new Intent(context, NotifReceiver.class).setAction(action);
    if (extras != null) {
        i.putExtras(extras);//from   w  ww .ja v a  2s .  co  m
    }

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

    long elapsed = mins * 60 * 1000;

    alarmMan.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + elapsed, pi);
}

From source file:org.xwalk.app.template.AppTemplateActivity.java

public static void set_RTC_wakeup(Context context) {

    Log.d(TAG, "setting RTC wakeup");

    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, UCCLauncherReceiver.class);
    intent.setAction(WAKEUP_SIG);/*from w  w w .j  av  a2  s  .c  o m*/
    alarmIntent_Wakeup = PendingIntent.getBroadcast(context, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, wakeup_rtc_time_hours);
    calendar.set(Calendar.MINUTE, wakeup_rtc_time_minutes);

    // cancel old intent (if any)
    alarmMgr.cancel(alarmIntent_Wakeup);

    // set new intent

    // alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    // SystemClock.elapsedRealtime() + 2 * 60 * 1000, alarmIntent_Wakeup);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            alarmIntent_Wakeup);
}

From source file:com.hodor.company.areminder.ui.MainActivity.java

private void registerAlarmManager(long duration) {
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(ACTION_SHOW_ALARM, null, this, TimerService.class);
    intent.putExtra("category", category.ordinal());
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    long time = System.currentTimeMillis() + duration;
    alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
}

From source file:com.aware.Aware.java

@Override
public void onCreate() {
    super.onCreate();

    awareContext = getApplicationContext();

    aware_preferences = getSharedPreferences("aware_core_prefs", MODE_PRIVATE);
    if (aware_preferences.getAll().isEmpty()) {
        SharedPreferences.Editor editor = aware_preferences.edit();
        editor.putInt(PREF_FREQUENCY_WATCHDOG, CONST_FREQUENCY_WATCHDOG);
        editor.putLong(PREF_LAST_SYNC, 0);
        editor.putLong(PREF_LAST_UPDATE, 0);
        editor.commit();/*from w w  w  .j a  v a 2 s. com*/
    }

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
    filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
    filter.addDataScheme("file");
    awareContext.registerReceiver(storage_BR, filter);

    filter = new IntentFilter();
    filter.addAction(Aware.ACTION_AWARE_CLEAR_DATA);
    filter.addAction(Aware.ACTION_AWARE_REFRESH);
    filter.addAction(Aware.ACTION_AWARE_SYNC_DATA);
    filter.addAction(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
    awareContext.registerReceiver(aware_BR, filter);

    alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

    awareStatusMonitor = new Intent(getApplicationContext(), Aware.class);
    repeatingIntent = PendingIntent.getService(getApplicationContext(), 0, awareStatusMonitor, 0);
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 1000,
            aware_preferences.getInt(PREF_FREQUENCY_WATCHDOG, 300) * 1000, repeatingIntent);

    Intent synchronise = new Intent(Aware.ACTION_AWARE_SYNC_DATA);
    webserviceUploadIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, synchronise, 0);

    if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        stopSelf();
    } else {
        SharedPreferences prefs = getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
        if (prefs.getAll().isEmpty()
                && Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
            PreferenceManager.setDefaultValues(getApplicationContext(), getPackageName(), Context.MODE_PRIVATE,
                    R.xml.aware_preferences, true);
            prefs.edit().commit(); //commit changes
        } else {
            PreferenceManager.setDefaultValues(getApplicationContext(), getPackageName(), Context.MODE_PRIVATE,
                    R.xml.aware_preferences, false);
        }

        Map<String, ?> defaults = prefs.getAll();
        for (Map.Entry<String, ?> entry : defaults.entrySet()) {
            if (Aware.getSetting(getApplicationContext(), entry.getKey()).length() == 0) {
                Aware.setSetting(getApplicationContext(), entry.getKey(), entry.getValue());
            }
        }

        if (Aware.getSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID).length() == 0) {
            UUID uuid = UUID.randomUUID();
            Aware.setSetting(getApplicationContext(), Aware_Preferences.DEVICE_ID, uuid.toString());
        }

        DEBUG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_FLAG).equals("true");
        TAG = Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG).length() > 0
                ? Aware.getSetting(awareContext, Aware_Preferences.DEBUG_TAG)
                : TAG;

        get_device_info();

        if (Aware.DEBUG)
            Log.d(TAG, "AWARE framework is created!");

        //Fixed: only the client application does a ping to AWARE's server
        if (getPackageName().equals("com.aware")) {
            new AsyncPing().execute();
        }
    }
}

From source file:org.sufficientlysecure.keychain.service.PassphraseCacheService.java

/**
 * Executed when service is started by intent
 *///from  www  . j a  v  a2s  .c o m
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand()");

    // register broadcastreceiver
    registerReceiver();

    if (intent != null && intent.getAction() != null) {
        if (ACTION_PASSPHRASE_CACHE_ADD.equals(intent.getAction())) {
            long ttl = intent.getLongExtra(EXTRA_TTL, DEFAULT_TTL);
            long keyId = intent.getLongExtra(EXTRA_KEY_ID, -1);
            String passphrase = intent.getStringExtra(EXTRA_PASSPHRASE);

            Log.d(TAG, "Received ACTION_PASSPHRASE_CACHE_ADD intent in onStartCommand() with keyId: " + keyId
                    + ", ttl: " + ttl);

            // add keyId and passphrase to memory
            mPassphraseCache.put(keyId, passphrase);

            if (ttl > 0) {
                // register new alarm with keyId for this passphrase
                long triggerTime = new Date().getTime() + (ttl * 1000);
                AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
                am.set(AlarmManager.RTC_WAKEUP, triggerTime, buildIntent(this, keyId));
            }
        } else if (ACTION_PASSPHRASE_CACHE_GET.equals(intent.getAction())) {
            long keyId = intent.getLongExtra(EXTRA_KEY_ID, -1);
            Messenger messenger = intent.getParcelableExtra(EXTRA_MESSENGER);

            String passphrase = getCachedPassphraseImpl(keyId);

            Message msg = Message.obtain();
            Bundle bundle = new Bundle();
            bundle.putString(EXTRA_PASSPHRASE, passphrase);
            msg.obj = bundle;
            try {
                messenger.send(msg);
            } catch (RemoteException e) {
                Log.e(Constants.TAG, "Sending message failed", e);
            }
        } else {
            Log.e(Constants.TAG, "Intent or Intent Action not supported!");
        }
    }

    return START_STICKY;
}

From source file:org.restcomm.app.qoslib.Services.TrackingManager.java

public void startCoverageTracking() {
    bTracking = true;/*  w  ww  .  j av  a  2s  . 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:org.yuttadhammo.BodhiTimer.TimerReceiver.java

@Override
public void onReceive(Context context, Intent pintent) {
    Log.v(TAG, "ALARM: received alarm");

    NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    if (player != null) {
        Log.v(TAG, "Releasing media player...");
        try {/*from   ww w  . j  a  v a 2  s  . c  o m*/
            player.release();
            player = null;
        } catch (Exception e) {
            e.printStackTrace();
            player = null;
        } finally {
            // do nothing
        }
    }

    // Cancel notification and return...
    if (CANCEL_NOTIFICATION.equals(pintent.getAction())) {
        Log.v(TAG, "Cancelling notification...");

        mNM.cancelAll();
        return;
    }

    // ...or display a new one

    Log.v(TAG, "Showing notification...");

    player = new MediaPlayer();

    int setTime = pintent.getIntExtra("SetTime", 0);
    String setTimeStr = TimerUtils.time2humanStr(context, setTime);
    Log.v(TAG, "Time: " + setTime);

    CharSequence text = context.getText(R.string.Notification);
    CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr);

    // Load the settings 
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    boolean led = prefs.getBoolean("LED", true);
    boolean vibrate = prefs.getBoolean("Vibrate", true);
    String notificationUri = "";

    boolean useAdvTime = prefs.getBoolean("useAdvTime", false);
    String advTimeString = prefs.getString("advTimeString", "");
    String[] advTime = null;
    int advTimeIndex = 1;

    if (useAdvTime && advTimeString.length() > 0) {
        advTime = advTimeString.split("\\^");
        advTimeIndex = prefs.getInt("advTimeIndex", 1);
        String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound

        if (thisAdvTime.length == 3)
            notificationUri = thisAdvTime[1];
        if (notificationUri.equals("sys_def"))
            notificationUri = prefs.getString("NotificationUri",
                    "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);
    } else
        notificationUri = prefs.getString("NotificationUri",
                "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell);

    Log.v(TAG, "notification uri: " + notificationUri);

    if (notificationUri.equals("system"))
        notificationUri = prefs.getString("SystemUri", "");
    else if (notificationUri.equals("file"))
        notificationUri = prefs.getString("FileUri", "");
    else if (notificationUri.equals("tts")) {
        notificationUri = "";
        final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done));
        Intent ttsIntent = new Intent(context, TTSService.class);
        ttsIntent.putExtra("spoken_text", ttsString);
        context.startService(ttsIntent);
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext())
            .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest);

    Uri uri = null;

    // Play a sound!
    if (!notificationUri.equals(""))
        uri = Uri.parse(notificationUri);

    // Vibrate
    if (vibrate && uri == null) {
        mBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
    }

    // Have a light
    if (led) {
        mBuilder.setLights(0xff00ff00, 300, 1000);
    }

    mBuilder.setAutoCancel(true);

    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, TimerActivity.class);

    // The stack builder object will contain an artificial back stack for the
    // started Activity.
    // This ensures that navigating backward from the Activity leads out of
    // your application to the Home screen.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(TimerActivity.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager mNotificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    // Create intent for cancelling the notification
    Context appContext = context.getApplicationContext();
    Intent intent = new Intent(appContext, TimerReceiver.class);
    intent.setAction(CANCEL_NOTIFICATION);

    // Cancel the pending cancellation and create a new one
    PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    if (uri != null) {

        //remove notification sound
        mBuilder.setSound(null);

        try {
            if (player != null && player.isPlaying()) {
                player.release();
                player = new MediaPlayer();
            }

            int currVolume = prefs.getInt("tone_volume", 0);
            if (currVolume != 0) {
                float log1 = (float) (Math.log(100 - currVolume) / Math.log(100));
                player.setVolume(1 - log1, 1 - log1);
            }
            player.setDataSource(context, uri);
            player.prepare();
            player.setLooping(false);
            player.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // TODO Auto-generated method stub
                    mp.release();
                }

            });
            player.start();
            if (vibrate) {
                Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
                vibrator.vibrate(1000);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (prefs.getBoolean("AutoClear", false)) {
        // Determine duration of notification sound
        int duration = 5000;
        if (uri != null) {
            MediaPlayer cancelPlayer = new MediaPlayer();
            try {
                cancelPlayer.setDataSource(context, uri);
                cancelPlayer.prepare();
                duration = Math.max(duration, cancelPlayer.getDuration() + 2000);
            } catch (java.io.IOException ex) {
                Log.e(TAG, "Cannot get sound duration: " + ex);
                duration = 30000; // on error, default to 30 seconds
            } finally {
                cancelPlayer.release();
            }
            cancelPlayer.release();
        }
        Log.v(TAG, "Notification duration: " + duration + " ms");
        // Schedule cancellation
        AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration,
                pendingCancelIntent);
    }

    if (useAdvTime && advTimeString.length() > 0) {
        Intent broadcast = new Intent();

        SharedPreferences.Editor editor = prefs.edit();
        if (advTimeIndex < advTime.length) {
            editor.putInt("advTimeIndex", advTimeIndex + 1);

            String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound

            int time = Integer.parseInt(thisAdvTime[0]);

            broadcast.putExtra("time", time);

            // Save new time
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);

            // editor.putString("NotificationUri", thisAdvTime[1]);

            mNM.cancelAll();
            Log.v(TAG, "Starting next iteration of the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);
        } else {
            broadcast.putExtra("stop", true);
            editor.putInt("advTimeIndex", 1);

        }
        broadcast.setAction(BROADCAST_RESET);
        context.sendBroadcast(broadcast);

        editor.apply();

    } else if (prefs.getBoolean("AutoRestart", false)) {
        int time = pintent.getIntExtra("SetTime", 0);
        if (time != 0) {

            mNM.cancel(0);
            Log.v(TAG, "Restarting the timer service ...");
            Intent rintent = new Intent(context, TimerReceiver.class);
            rintent.putExtra("SetTime", time);
            PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent);

            // Save new time
            SharedPreferences.Editor editor = prefs.edit();
            editor.putLong("TimeStamp", new Date().getTime() + time);
            editor.putInt("LastTime", time);
            editor.apply();

            Intent broadcast = new Intent();
            broadcast.putExtra("time", time);
            broadcast.setAction(BROADCAST_RESET);
            context.sendBroadcast(broadcast);

        }
    }

    mNotificationManager.notify(0, mBuilder.build());

    Log.d(TAG, "ALARM: alarm finished");

}

From source file:org.xwalk.app.template.AppTemplateActivity.java

public static void set_RTC_sleep(Context context) {

    Log.d(TAG, "setting RTC sleep");

    alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, UCCLauncherReceiver.class);
    intent.setAction(SLEEP_SIG);//from   www. jav  a2s  . c  om
    alarmIntent_Sleep = PendingIntent.getBroadcast(context, 0, intent, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, sleep_rtc_time_hours);
    calendar.set(Calendar.MINUTE, sleep_rtc_time_minutes);

    // cancel old intent (if any)
    alarmMgr.cancel(alarmIntent_Sleep);

    // set new intent

    // alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
    // SystemClock.elapsedRealtime() + 2 * 60 * 1000, alarmIntent_Sleep);

    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
            alarmIntent_Sleep);

}

From source file:shetye.prathamesh.notifyme.Utilities.java

private void setZoneInTimer(Context context, Notif note) {
    Intent intent = new Intent(context, RecieveAndNotify.class);
    intent.setData(Uri.parse(Integer.toString(note.get_id())));
    intent.setAction(NOTIF_SERVICE_ACTION);
    intent.putExtra(NOTIF_EXTRA_TITLE_KEY, note.getNotification_title());
    intent.putExtra(NOTIF_EXTRA_KEY, note.getNotification_content());
    intent.putExtra(NOTIF_EXTRA_ID_KEY, note.get_id());
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, note.getNotification_when(), PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.nextgis.mobile.services.TrackerService.java

protected void ScheduleNextUpdate(Context context, String action, long nMinTimeBetweenSend,
        boolean bEnergyEconomy, boolean bStart) {
    if (context == null)
        return;/*from   w ww . j av  a  2 s  . co m*/
    Log.d(TAG, "Schedule Next Update for tracker " + bStart);
    if (bStart == false)
        return;
    Intent intent = new Intent(action);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // The update frequency should often be user configurable.  This is not.

    long currentTimeMillis = System.currentTimeMillis();
    long nextUpdateTimeMillis = currentTimeMillis + nMinTimeBetweenSend;
    Time nextUpdateTime = new Time();
    nextUpdateTime.set(nextUpdateTimeMillis);

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    if (bEnergyEconomy)
        alarmManager.set(AlarmManager.RTC, nextUpdateTimeMillis, pendingIntent);
    else
        alarmManager.set(AlarmManager.RTC_WAKEUP, nextUpdateTimeMillis, pendingIntent);
}