Example usage for android.app AlarmManager ELAPSED_REALTIME

List of usage examples for android.app AlarmManager ELAPSED_REALTIME

Introduction

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

Prototype

int ELAPSED_REALTIME

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

Click Source Link

Document

Alarm time in android.os.SystemClock#elapsedRealtime SystemClock.elapsedRealtime() (time since boot, including sleep).

Usage

From source file:com.radioactiveyak.location_best_practices.services.PlaceCheckinService.java

/**
 * {@inheritDoc}//from   www . j  a v  a  2  s .  c  o  m
 * Perform a checkin the specified venue. If the checkin fails, add it to the queue and
 * set an alarm to retry.
 * 
 * Query the checkin queue to see if there are pending checkins to be retried.
 */
@Override
protected void onHandleIntent(Intent intent) {
    // Retrieve the details for the checkin to perform.
    String reference = intent.getStringExtra(PlacesConstants.EXTRA_KEY_REFERENCE);
    String id = intent.getStringExtra(PlacesConstants.EXTRA_KEY_ID);
    long timeStamp = intent.getLongExtra(PlacesConstants.EXTRA_KEY_TIME_STAMP, 0);

    // Check if we're running in the foreground, if not, check if
    // we have permission to do background updates.
    boolean backgroundAllowed = cm.getBackgroundDataSetting();
    boolean inBackground = sharedPreferences.getBoolean(PlacesConstants.EXTRA_KEY_IN_BACKGROUND, true);

    if (reference != null && !backgroundAllowed && inBackground) {
        addToQueue(timeStamp, reference, id);
        return;
    }

    // Check to see if we are connected to a data network.
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    // If we're not connected then disable the retry Alarm, enable the Connectivity Changed Receiver
    // and add the new checkin directly to the queue. The Connectivity Changed Receiver will listen
    // for when we connect to a network and start this service to retry the checkins.
    if (!isConnected) {
        // No connection so no point triggering an alarm to retry until we're connected.
        alarmManager.cancel(retryQueuedCheckinsPendingIntent);

        // Enable the Connectivity Changed Receiver to listen for connection to a network
        // so we can commit the pending checkins.
        PackageManager pm = getPackageManager();
        ComponentName connectivityReceiver = new ComponentName(this, ConnectivityChangedReceiver.class);
        pm.setComponentEnabledSetting(connectivityReceiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);

        // Add this checkin to the queue.
        addToQueue(timeStamp, reference, id);
    } else {
        // Execute the checkin. If it fails, add it to the retry queue.
        if (reference != null) {
            if (!checkin(timeStamp, reference, id))
                addToQueue(timeStamp, reference, id);
        }

        // Retry the queued checkins.
        ArrayList<String> successfulCheckins = new ArrayList<String>();
        Cursor queuedCheckins = contentResolver.query(QueuedCheckinsContentProvider.CONTENT_URI, null, null,
                null, null);
        try {
            // Retry each checkin.
            while (queuedCheckins.moveToNext()) {
                long queuedTimeStamp = queuedCheckins
                        .getLong(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_TIME_STAMP));
                String queuedReference = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_REFERENCE));
                String queuedId = queuedCheckins
                        .getString(queuedCheckins.getColumnIndex(QueuedCheckinsContentProvider.KEY_ID));
                if (queuedReference == null || checkin(queuedTimeStamp, queuedReference, queuedId))
                    successfulCheckins.add(queuedReference);
            }

            // Delete the queued checkins that were successful.
            if (successfulCheckins.size() > 0) {
                StringBuilder sb = new StringBuilder("(" + QueuedCheckinsContentProvider.KEY_REFERENCE + "='"
                        + successfulCheckins.get(0) + "'");
                for (int i = 1; i < successfulCheckins.size(); i++)
                    sb.append(" OR " + QueuedCheckinsContentProvider.KEY_REFERENCE + " = '"
                            + successfulCheckins.get(i) + "'");
                sb.append(")");
                int deleteCount = contentResolver.delete(QueuedCheckinsContentProvider.CONTENT_URI,
                        sb.toString(), null);
                Log.d(TAG, "Deleted: " + deleteCount);
            }

            // If there are still queued checkins then set a non-waking alarm to retry them.
            queuedCheckins.requery();
            if (queuedCheckins.getCount() > 0) {
                long triggerAtTime = System.currentTimeMillis() + PlacesConstants.CHECKIN_RETRY_INTERVAL;
                alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtTime,
                        retryQueuedCheckinsPendingIntent);
            } else
                alarmManager.cancel(retryQueuedCheckinsPendingIntent);
        } finally {
            queuedCheckins.close();
        }
    }
}

From source file:com.uphyca.idobata.android.service.IdobataService.java

private void executeAt(long triggerAtMillis) {
    PendingIntent pi = buildPendingStartServiceIntent();
    mAlarmManager.cancel(pi);/*from  w  w w  .j a  v  a  2s  .c  o  m*/
    mAlarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtMillis, pi);
}

From source file:nu.yona.app.api.service.ActivityMonitorService.java

private void restartService() {
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1,
            restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + AppConstant.ONE_SECOND,
            restartServicePendingIntent);

}

From source file:org.smssecure.smssecure.service.KeyCachingService.java

private void startTimeoutIfAppropriate() {
    boolean timeoutEnabled = SilencePreferences.isPassphraseTimeoutEnabled(this);

    if ((activitiesRunning == 0) && (KeyCachingService.masterSecret != null) && timeoutEnabled
            && !SilencePreferences.isPasswordDisabled(this)) {
        long timeoutMinutes = SilencePreferences.getPassphraseTimeoutInterval(this);
        long timeoutMillis = TimeUnit.MINUTES.toMillis(timeoutMinutes);

        Log.w("KeyCachingService", "Starting timeout: " + timeoutMillis);

        AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pending);/*from   w w w  . j  a  va 2 s. c o m*/
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeoutMillis, pending);
    }
}

From source file:com.tingtingapps.securesms.service.KeyCachingService.java

private void startTimeoutIfAppropriate() {
    boolean timeoutEnabled = TextSecurePreferences.isPassphraseTimeoutEnabled(this);

    if ((activitiesRunning == 0) && (KeyCachingService.masterSecret != null) && timeoutEnabled
            && !TextSecurePreferences.isPasswordDisabled(this)) {
        long timeoutMinutes = TextSecurePreferences.getPassphraseTimeoutInterval(this);
        long timeoutMillis = TimeUnit.MINUTES.toMillis(timeoutMinutes);

        Log.w("KeyCachingService", "Starting timeout: " + timeoutMillis);

        AlarmManager alarmManager = (AlarmManager) this.getSystemService(ALARM_SERVICE);
        alarmManager.cancel(pending);//from  ww  w.  j  a v  a2s  .  c  om
        alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + timeoutMillis, pending);
    }
}

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 {// ww  w . j a v  a  2  s  .  co  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:id.ridon.keude.UpdateService.java

public static void schedule(Context ctx) {

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    String sint = prefs.getString(Preferences.PREF_UPD_INTERVAL, "0");
    int interval = Integer.parseInt(sint);

    Intent intent = new Intent(ctx, UpdateService.class);
    PendingIntent pending = PendingIntent.getService(ctx, 0, intent, 0);

    AlarmManager alarm = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pending);// ww w  .jav a 2s  . c o  m
    if (interval > 0) {
        alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 5000,
                AlarmManager.INTERVAL_HOUR, pending);
        Log.d("Keude", "Update scheduler alarm set");
    } else {
        Log.d("Keude", "Update scheduler alarm not set");
    }

}

From source file:de.quist.app.errorreporter.ExceptionReportService.java

private void sendReport(Intent intent) throws UnsupportedEncodingException, NameNotFoundException {
    Log.v(TAG, "Got request to report error: " + intent.toString());
    Uri server = getTargetUrl();/*from w w  w . j  av  a2  s . c o  m*/

    boolean isManualReport = intent.getBooleanExtra(EXTRA_MANUAL_REPORT, false);
    boolean isReportOnFroyo = isReportOnFroyo();
    boolean isFroyoOrAbove = isFroyoOrAbove();
    if (isFroyoOrAbove && !isManualReport && !isReportOnFroyo) {
        // We don't send automatic reports on froyo or above
        Log.d(TAG, "Don't send automatic report on froyo");
        return;
    }

    Set<String> fieldsToSend = getFieldsToSend();

    String stacktrace = intent.getStringExtra(EXTRA_STACK_TRACE);
    String exception = intent.getStringExtra(EXTRA_EXCEPTION_CLASS);
    String message = intent.getStringExtra(EXTRA_MESSAGE);
    long availableMemory = intent.getLongExtra(EXTRA_AVAILABLE_MEMORY, -1l);
    long totalMemory = intent.getLongExtra(EXTRA_TOTAL_MEMORY, -1l);
    String dateTime = intent.getStringExtra(EXTRA_EXCEPTION_TIME);
    String threadName = intent.getStringExtra(EXTRA_THREAD_NAME);
    String extraMessage = intent.getStringExtra(EXTRA_EXTRA_MESSAGE);
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    addNameValuePair(params, fieldsToSend, "exStackTrace", stacktrace);
    addNameValuePair(params, fieldsToSend, "exClass", exception);
    addNameValuePair(params, fieldsToSend, "exDateTime", dateTime);
    addNameValuePair(params, fieldsToSend, "exMessage", message);
    addNameValuePair(params, fieldsToSend, "exThreadName", threadName);
    if (extraMessage != null)
        addNameValuePair(params, fieldsToSend, "extraMessage", extraMessage);
    if (availableMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devAvailableMemory", availableMemory + "");
    if (totalMemory >= 0)
        addNameValuePair(params, fieldsToSend, "devTotalMemory", totalMemory + "");

    PackageManager pm = getPackageManager();
    try {
        PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), 0);
        addNameValuePair(params, fieldsToSend, "appVersionCode", packageInfo.versionCode + "");
        addNameValuePair(params, fieldsToSend, "appVersionName", packageInfo.versionName);
        addNameValuePair(params, fieldsToSend, "appPackageName", packageInfo.packageName);
    } catch (NameNotFoundException e) {
    }
    addNameValuePair(params, fieldsToSend, "devModel", android.os.Build.MODEL);
    addNameValuePair(params, fieldsToSend, "devSdk", android.os.Build.VERSION.SDK);
    addNameValuePair(params, fieldsToSend, "devReleaseVersion", android.os.Build.VERSION.RELEASE);

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost post = new HttpPost(server.toString());
    post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    Log.d(TAG, "Created post request");

    try {
        httpClient.execute(post);
        Log.v(TAG, "Reported error: " + intent.toString());
    } catch (ClientProtocolException e) {
        // Ignore this kind of error
        Log.e(TAG, "Error while sending an error report", e);
    } catch (SSLException e) {
        Log.e(TAG, "Error while sending an error report", e);
    } catch (IOException e) {
        if (e instanceof SocketException && e.getMessage().contains("Permission denied")) {
            Log.e(TAG, "You don't have internet permission", e);
        } else {
            int maximumRetryCount = getMaximumRetryCount();
            int maximumExponent = getMaximumBackoffExponent();
            // Retry at a later point in time
            AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
            int exponent = intent.getIntExtra(EXTRA_CURRENT_RETRY_COUNT, 0);
            intent.putExtra(EXTRA_CURRENT_RETRY_COUNT, exponent + 1);
            PendingIntent operation = PendingIntent.getService(this, 0, intent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (exponent >= maximumRetryCount) {
                // Discard error
                Log.w(TAG, "Error report reached the maximum retry count and will be discarded.\nStacktrace:\n"
                        + stacktrace);
                return;
            }
            if (exponent > maximumExponent) {
                exponent = maximumExponent;
            }
            long backoff = (1 << exponent) * 1000; // backoff in ms
            alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + backoff, operation);
        }
    }
}

From source file:com.google.android.gcm.GCMBaseIntentService.java

private void handleRegistration(final Context context, Intent intent) {
    String registrationId = intent.getStringExtra(EXTRA_REGISTRATION_ID);
    String error = intent.getStringExtra(EXTRA_ERROR);
    String unregistered = intent.getStringExtra(EXTRA_UNREGISTERED);
    Log.d(TAG, "handleRegistration: registrationId = " + registrationId + ", error = " + error
            + ", unregistered = " + unregistered);

    // registration succeeded
    if (registrationId != null) {
        GCMRegistrar.resetBackoff(context);
        GCMRegistrar.setRegistrationId(context, registrationId);
        onRegistered(context, registrationId);
        return;//ww w .j  a  v  a 2 s. c  o  m
    }

    // unregistration succeeded
    if (unregistered != null) {
        // Remember we are unregistered
        GCMRegistrar.resetBackoff(context);
        String oldRegistrationId = GCMRegistrar.clearRegistrationId(context);
        onUnregistered(context, oldRegistrationId);
        return;
    }

    // last operation (registration or unregistration) returned an error;
    Log.d(TAG, "Registration error: " + error);
    // Registration failed
    if (ERROR_SERVICE_NOT_AVAILABLE.equals(error)) {
        boolean retry = onRecoverableError(context, error);
        if (retry) {
            int backoffTimeMs = GCMRegistrar.getBackoff(context);
            int nextAttempt = backoffTimeMs / 2 + sRandom.nextInt(backoffTimeMs);
            Log.d(TAG, "Scheduling registration retry, backoff = " + nextAttempt + " (" + backoffTimeMs + ")");
            Intent retryIntent = new Intent(INTENT_FROM_GCM_LIBRARY_RETRY);
            retryIntent.putExtra(EXTRA_TOKEN, TOKEN);
            PendingIntent retryPendingIntent = PendingIntent.getBroadcast(context, 0, retryIntent, 0);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            am.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + nextAttempt,
                    retryPendingIntent);
            // Next retry should wait longer.
            if (backoffTimeMs < MAX_BACKOFF_MS) {
                GCMRegistrar.setBackoff(context, backoffTimeMs * 2);
            }
        } else {
            Log.d(TAG, "Not retrying failed operation");
        }
    } else {
        // Unrecoverable error, notify app
        onError(context, error);
    }
}

From source file:com.granita.tasks.notification.NotificationActionUtils.java

/**
 * Registers a timeout for the undo notification such that when it expires, the undo bar will disappear, and the action will be performed.
 *//*from w  w w.  j a  va  2  s .  c om*/
public static void registerUndoTimeout(final Context context, final NotificationAction notificationAction) {

    if (sUndoTimeoutMillis == -1) {
        sUndoTimeoutMillis = TIMEOUT_MILLIS;
    }

    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final long triggerAtMills = SystemClock.elapsedRealtime() + sUndoTimeoutMillis;
    final PendingIntent pendingIntent = createUndoTimeoutPendingIntent(context, notificationAction);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME, triggerAtMills, pendingIntent);
}