Example usage for android.app AlarmManager RTC

List of usage examples for android.app AlarmManager RTC

Introduction

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

Prototype

int RTC

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

Click Source Link

Document

Alarm time in System#currentTimeMillis System.currentTimeMillis() (wall clock time in UTC).

Usage

From source file:im.vector.activity.CommonActivityUtils.java

/**
 * Restart the application after 100ms/*w ww  . j a  v a 2s.  c  o m*/
 * @param activity activity
 */
public static void restartApp(Context activity) {
    PendingIntent mPendingIntent = PendingIntent.getActivity(activity, 314159,
            new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

    // so restart the application after 100ms
    AlarmManager mgr = (AlarmManager) activity.getSystemService(activity.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);
    System.exit(0);
}

From source file:com.chess.genesis.net.GenesisNotifier.java

public static void ScheduleWakeup(final Context context) {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.MINUTE, Pref.getInt(context, R.array.pf_notifierPolling));
    final long start = cal.getTimeInMillis();
    final long interval = start - System.currentTimeMillis();

    final Intent intent = new Intent(context, GenesisAlarm.class);
    final PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.RTC, start, interval, pintent);
}

From source file:org.onebusaway.android.directions.realtime.RealtimeService.java

private void startRealtimeUpdates(Bundle params, Itinerary itinerary) {

    Log.d(TAG, "Checking whether to start realtime updates.");

    boolean realtimeLegsOnItineraries = false;

    for (Leg leg : itinerary.legs) {
        if (leg.realTime) {
            realtimeLegsOnItineraries = true;
        }// w  ww.  j  a va  2 s. c  o m
    }

    if (realtimeLegsOnItineraries) {
        Log.d(TAG, "Starting realtime updates for itinerary");

        // init alarm mgr
        getAlarmManager().setInexactRepeating(AlarmManager.RTC, new Date().getTime(),
                OTPConstants.DEFAULT_UPDATE_INTERVAL_TRIP_TIME, getAlarmIntent(params));
    } else {
        Log.d(TAG, "No realtime legs on itinerary");
    }

}

From source file:net.texh.cordovapluginstepcounter.StepCounterService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "onStartCommand");

    SharedPreferences sharedPref = getSharedPreferences(CordovaStepCounter.USER_DATA_PREF,
            Context.MODE_PRIVATE);
    Boolean pActive = CordovaStepCounter.getPedometerIsActive(sharedPref);

    //Service should not be activated (pedometer stopped by user)
    if (!pActive) {
        Log.i(TAG,/*from   w  w  w. java2 s .c  om*/
                "/!\\ onStartCommand Ask to stopSelf, should not be launched ! Should not even be here (maybe 4.4.2 specific bug causes a restart here)");
        stopSelf();
        return START_NOT_STICKY;
    }

    Log.i(TAG, "- Relaunch service in 1 hour (4.4.2 start_sticky bug ) : ");
    Intent newServiceIntent = new Intent(this, StepCounterService.class);
    AlarmManager aManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent stepIntent = PendingIntent.getService(getApplicationContext(), 10, newServiceIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    //PendingIntent.GetService (ApplicationContext, 10, intent2, PendingIntentFlags.UpdateCurrent);
    aManager.set(AlarmManager.RTC, java.lang.System.currentTimeMillis() + 1000 * 60 * 60, stepIntent);

    if (isRunning /* || has no step sensors */) {
        Log.i(TAG, "Not initialising sensors");
        return Service.START_STICKY;
    }

    Log.i(TAG, "Initialising sensors");
    doInit();

    isRunning = true;
    return Service.START_STICKY;
}

From source file:damo.three.ie.prepay.UpdateService.java

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    try {//from   w  w w  . jav  a2 s . c o  m
        Log.d(Constants.TAG, "Fetching usages from service.");
        UsageFetcher usageFetcher = new UsageFetcher(context, true);
        JSONArray usages = usageFetcher.getUsages();

        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences sharedUsagePref = context.getSharedPreferences("damo.three.ie.previous_usage",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedUsagePref.edit();
        editor.putLong("last_refreshed_milliseconds", new DateTime().getMillis());
        editor.putString("usage_info", usages.toString());
        editor.commit();

        // Register alarms for newly refreshed usages in background
        boolean notificationsEnabled = sharedPref.getBoolean("notification", true);
        List<UsageItem> usageItems = JSONUtils.jsonToUsageItems(usages);
        List<BasicUsageItem> basicUsageItems = UsageUtils.getAllBasicItems(usageItems);
        UsageUtils.registerInternetExpireAlarm(context, basicUsageItems, notificationsEnabled, true);

    } catch (Exception e) {
        // Try again at 7pm, unless its past 7pm. Then forget and let tomorrow's alarm do the updating.
        // Still trying to decide if I need a more robust retry mechanism.
        Log.d(Constants.TAG, "Caught exception: " + e.getLocalizedMessage());
        Calendar calendar = Calendar.getInstance();
        if (calendar.get(Calendar.HOUR_OF_DAY) < Constants.HOUR_TO_RETRY) {
            Log.d(Constants.TAG, "Scheduling a re-try for 7pm");
            calendar.set(Calendar.HOUR_OF_DAY, Constants.HOUR_TO_RETRY);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);

            Intent receiver = new Intent(context, UpdateReceiver.class);
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Using different request code to 0 so it won't conflict with other alarm below.
            PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3, receiver,
                    PendingIntent.FLAG_UPDATE_CURRENT);

            // Keeping efficiency in mind:
            // http://developer.android.com/reference/android/app/AlarmManager.html#ELAPSED_REALTIME
            am.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
        }
    } finally {
        Log.d(Constants.TAG, "Finish UpdateService");
        UpdateReceiver.completeWakefulIntent(intent);
    }
}

From source file:org.voidsink.anewjkuapp.activity.SettingsActivity.java

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

    PreferenceManager.getDefaultSharedPreferences(this).unregisterOnSharedPreferenceChangeListener(this);

    if (mThemeChanged) {
        Log.i(TAG, "theme changed");

        AlarmManager alm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alm.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,
                PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0));

        android.os.Process.killProcess(android.os.Process.myPid());
    }/*from  ww w .j a  va  2  s  . c om*/
}

From source file:com.nbplus.vbroadlistener.gcm.RegistrationIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    String action = intent.getAction();
    String token = null;//from  ww w  .j  a  v a2s  . c  om
    if (Constants.REGISTER_GCM.equals(action) || Constants.UPDATE_GCM.equals(action)) {
        try {
            // In the (unlikely) event that multiple refresh operations occur simultaneously,
            // ensure that they are processed sequentially.
            synchronized (TAG) {

                // [START register_for_gcm]
                // Initially this call goes out to the network to retrieve the token, subsequent calls
                // are local.
                // [START get_token]
                LauncherSettings.getInstance(this).setGcmToken("");
                LauncherSettings.getInstance(this).setGcmSentToServerStatus(false);
                LauncherSettings.getInstance(this).setGcmRegisteredStatus(false);

                InstanceID instanceID = InstanceID.getInstance(this);
                token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE,
                        null);
                // [END get_token]
                Log.i(TAG, "GCM Registration Token: " + token);

                /**
                 * 2015.07.17
                 * ??  ?? ? ... ? ?  ?
                 *  ?? ?  ?? ?? ? Native? .
                 */
                if (Constants.UPDATE_GCM.equals(action)) {
                    boolean result = sendRegistrationToServer(token);
                    LauncherSettings.getInstance(this).setGcmSentToServerStatus(result);
                    if (!result) {
                        Log.i(TAG, "setAlarm() = 5min");
                        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

                        Intent i = new Intent(this, RegistrationIntentService.class);
                        i.setAction(Constants.UPDATE_GCM);
                        PendingIntent pIntent = PendingIntent.getService(this, 0, i, 0);

                        alarmManager.set(AlarmManager.RTC, System.currentTimeMillis() + 60 * 5 * 1000, pIntent);
                        startService(i);
                    }
                } else {
                    LauncherSettings.getInstance(this).setGcmSentToServerStatus(true);
                    // Subscribe to topic channels
                    subscribeTopics(token);
                }

                // You should store a boolean that indicates whether the generated token has been
                // sent to your server. If the boolean is false, send the token to your server,
                // otherwise your server should have already received the token.
                LauncherSettings.getInstance(this).setGcmRegisteredStatus(true);
                LauncherSettings.getInstance(this).setGcmToken(token);
                // [END register_for_gcm]
            }
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
            LauncherSettings.getInstance(this).setGcmSentToServerStatus(false);
            if (!StringUtils.isEmptyString(token)) {
                LauncherSettings.getInstance(this).setGcmToken(token);
                LauncherSettings.getInstance(this).setGcmRegisteredStatus(true);
            }
        }
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Constants.REGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    } else if (Constants.UNREGISTER_GCM.equals(action)) {
        try {
            // In the (unlikely) event that multiple refresh operations occur simultaneously,
            // ensure that they are processed sequentially.
            synchronized (TAG) {

                // [START register_for_gcm]
                // Initially this call goes out to the network to retrieve the token, subsequent calls
                // are local.
                // [START get_token]
                InstanceID instanceID = InstanceID.getInstance(this);
                token = instanceID.getToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE,
                        null);
                // TODO: Implement this method to send any registration to your app's servers.
                sendUnRegistrationToServer(token);

                // Subscribe to topic channels
                unSubscribeTopics(token);

                instanceID.deleteToken(Constants.GCM_SENDER_ID, GoogleCloudMessaging.INSTANCE_ID_SCOPE);
                // [END get_token]
                Log.i(TAG, "GCM Registration Token: " + token);

                // You should store a boolean that indicates whether the generated token has been
                // sent to your server. If the boolean is false, send the token to your server,
                // otherwise your server should have already received the token.
                LauncherSettings.getInstance(this).setGcmSentToServerStatus(false);
                LauncherSettings.getInstance(this).setGcmRegisteredStatus(false);
                LauncherSettings.getInstance(this).setGcmToken("");
                // [END register_for_gcm]
            }
        } catch (Exception e) {
            Log.d(TAG, "Failed to complete token refresh", e);
            // If an exception happens while fetching the new token or updating our registration data
            // on a third-party server, this ensures that we'll attempt the update at a later time.
            LauncherSettings.getInstance(this).setGcmSentToServerStatus(false);
            LauncherSettings.getInstance(this).setGcmRegisteredStatus(false);
            LauncherSettings.getInstance(this).setGcmToken("");
        }
        // Notify UI that registration has completed, so the progress indicator can be hidden.
        Intent registrationComplete = new Intent(Constants.UNREGISTRATION_COMPLETE);
        LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
    }
}

From source file:org.bwgz.quotation.service.QuotationService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG, String.format("onHandleIntent - intent: %s (%s)", intent, new Date().toString()));

    SharedPreferences preferences = getSharedPreferences(QuotationApplication.APPLICATION_PREFERENCES,
            Context.MODE_PRIVATE);
    long modified = preferences.getLong(QuotationApplication.APPLICATION_PREFERENCE_QUOTATION_PICKS_MODIFIED,
            0);//from  w ww  .j a va  2s  .c om

    if (modified + PICKS_PERIOD < System.currentTimeMillis()) {
        getContentResolver().delete(PickQuotation.CONTENT_URI, null, null);
        getContentResolver().delete(PickPerson.CONTENT_URI, null, null);
        getContentResolver().delete(PickSubject.CONTENT_URI, null, null);

        FreebaseIdLoader freebaseIdLoader = FreebaseIdLoader.getInstance(getApplicationContext());
        List<Pick> quotationPicks = freebaseIdLoader.getRandomQuotationPicks(PICK_SIZE);
        List<Pick> authorPicks = freebaseIdLoader.getRandomAuthorPicks(PICK_SIZE);
        List<Pick> subjectPicks = freebaseIdLoader.getRandomSubjectPicks(PICK_SIZE);

        for (int i = 0; i < PICK_SIZE; i++) {
            getContentResolver()
                    .query(PickQuotation.withAppendedId(quotationPicks.get(i).getId()), null, null, null, null)
                    .close();
            getContentResolver()
                    .query(PickPerson.withAppendedId(authorPicks.get(i).getId()), null, null, null, null)
                    .close();
            getContentResolver()
                    .query(PickSubject.withAppendedId(subjectPicks.get(i).getId()), null, null, null, null)
                    .close();
        }

        SharedPreferences.Editor editor = preferences.edit();
        modified = System.currentTimeMillis();
        editor.putLong(QuotationApplication.APPLICATION_PREFERENCE_QUOTATION_PICKS_MODIFIED, modified);
        editor.putLong(QuotationApplication.APPLICATION_PREFERENCE_PERSON_PICKS_MODIFIED, modified);
        editor.putLong(QuotationApplication.APPLICATION_PREFERENCE_SUBJECT_PICKS_MODIFIED, modified);
        editor.commit();
    }

    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0,
            new Intent(this, QuotationAlarmReceiver.class), 0);
    alarmManager.cancel(alarmIntent);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, 2);
    calendar.set(Calendar.MINUTE, random.nextInt(60));
    calendar.set(Calendar.SECOND, random.nextInt(60));
    alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis() + PICKS_PERIOD, alarmIntent);

    LocalBroadcastManager.getInstance(this)
            .sendBroadcast(new Intent(BROADCAST_ACTION).putExtra(EXTENDED_DATA_STATUS, true));
}

From source file:com.kubotaku.android.code4kyoto5374.util.AlarmService.java

@TargetApi(Build.VERSION_CODES.M)
private static void setupAlarmNew(Context context, PendingIntent intent, final long triggerAtMillis) {
    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setAndAllowWhileIdle(AlarmManager.RTC, triggerAtMillis, intent);
}

From source file:com.kubotaku.android.code4kyoto5374.util.AlarmService.java

private static void setupAlarmOld(Context context, PendingIntent intent, final long triggerAtMillis) {
    final AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, triggerAtMillis, intent);
}