Example usage for android.content Context ALARM_SERVICE

List of usage examples for android.content Context ALARM_SERVICE

Introduction

In this page you can find the example usage for android.content Context ALARM_SERVICE.

Prototype

String ALARM_SERVICE

To view the source code for android.content Context ALARM_SERVICE.

Click Source Link

Document

Use with #getSystemService(String) to retrieve a android.app.AlarmManager for receiving intents at a time of your choosing.

Usage

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;// www.j  a  v a2 s .  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:com.etime.ETimeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}

From source file:com.cyanogenmod.account.util.CMAccountUtils.java

public static void cancelCMAccountPing(Context context, Intent intent) {
    if (CMAccount.DEBUG)
        Log.d(TAG, "Canceling CMAccount ping");
    PendingIntent reRegisterPendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(reRegisterPendingIntent);/*from   w  w  w .j a  va  2s .  co m*/
}

From source file:de.wikilab.android.friendica01.Max.java

public static void cancelTimer(Context c) {
    Log.i("Friendica", "try cancelTimer");
    if (piTimerNotifications == null)
        return;/*from  w  w  w  .j ava2 s .co  m*/
    AlarmManager a = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);
    a.cancel(piTimerNotifications);
    piTimerNotifications = null;
    Toast.makeText(c, "Friendica: Notif. check timer cancel", Toast.LENGTH_SHORT).show();
    Log.i("Friendica", "done cancelTimer");
}

From source file:com.phonemetra.account.util.AccountUtils.java

public static void cancelAccountPing(Context context, Intent intent) {
    if (Account.DEBUG)
        Log.d(TAG, "Canceling Account ping");
    PendingIntent reRegisterPendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(reRegisterPendingIntent);/*from  ww w  .  ja va2 s .  c  o m*/
}

From source file:com.svpino.longhorn.MarketCollectorService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
    long lastUpdate = sharedPreferences.getLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, 0);
    boolean retrying = sharedPreferences.getBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
    int retries = sharedPreferences.getInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
    boolean wereWeWaitingForConnectivity = sharedPreferences
            .getBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);

    boolean isGlobalCollection = intent.getExtras() == null
            || (intent.getExtras() != null && !intent.getExtras().containsKey(EXTRA_TICKER));

    if (wereWeWaitingForConnectivity) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);
        editor.commit();//from   w  ww .  j ava  2  s  . c  om
    }

    if (retrying && isGlobalCollection) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
        editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
        editor.commit();

        ((AlarmManager) getSystemService(Context.ALARM_SERVICE))
                .cancel(Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
    }

    long currentTime = System.currentTimeMillis();
    if (retrying || wereWeWaitingForConnectivity || !isGlobalCollection
            || (isGlobalCollection && currentTime - lastUpdate > Constants.COLLECTOR_MIN_REFRESH_INTERVAL)) {
        String[] tickers = null;

        if (isGlobalCollection) {
            Log.d(LOG_TAG, "Executing global market information collection...");
            tickers = DataProvider.getStockDataTickers(this);
        } else {
            String ticker = intent.getExtras().containsKey(EXTRA_TICKER)
                    ? intent.getExtras().getString(EXTRA_TICKER)
                    : null;

            Log.d(LOG_TAG, "Executing market information collection for ticker " + ticker + ".");

            tickers = new String[] { ticker };
        }

        try {
            collect(tickers);

            if (isGlobalCollection) {
                Editor editor = sharedPreferences.edit();
                editor.putLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, System.currentTimeMillis());
                editor.commit();
            }

            DataProvider.notifyDataCollectionIsFinished(this, tickers);

            Log.d(LOG_TAG, "Market information collection was successfully completed");
        } catch (Exception e) {
            Log.e(LOG_TAG, "Market information collection failed.", e);

            if (Extensions.areWeOnline(this)) {
                Log.d(LOG_TAG, "Scheduling an alarm for retrying a global market information collection...");

                retries++;

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, true);
                editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, retries);
                editor.commit();

                long interval = Constants.COLLECTOR_MIN_RETRY_INTERVAL * retries;
                if (interval > Constants.COLLECTOR_MAX_REFRESH_INTERVAL) {
                    interval = Constants.COLLECTOR_MAX_REFRESH_INTERVAL;
                }

                ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC,
                        System.currentTimeMillis() + interval,
                        Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
            } else {
                Log.d(LOG_TAG,
                        "It appears that we are not online, so let's start listening for connectivity updates.");

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, true);
                editor.commit();

                ComponentName componentName = new ComponentName(this, ConnectivityBroadcastReceiver.class);
                getPackageManager().setComponentEnabledSetting(componentName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }
        }
    } else if (isGlobalCollection && currentTime - lastUpdate <= Constants.COLLECTOR_MIN_REFRESH_INTERVAL) {
        Log.d(LOG_TAG, "Global market information collection will be skipped since it was performed less than "
                + (Constants.COLLECTOR_MIN_REFRESH_INTERVAL / 60 / 1000) + " minutes ago.");
    }

    stopSelf();
}

From source file:jieehd.villain.updater.VillainUpdater.java

public void setRepeatingAlarm() {
    AlarmManager am;/*from   www  .j  a va2 s  . c om*/
    am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, checkInBackground.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), (3 * AlarmManager.INTERVAL_DAY),
            pendingIntent);
}

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   w ww  .  jav a2s  .co  m
}

From source file:com.example.android.wearable.timer.SetTimerActivity.java

private void registerWithAlarmManager(long duration) {
    // Get the alarm manager.
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    // Create intent that gets fired when timer expires.
    Intent intent = new Intent(Constants.ACTION_SHOW_ALARM, null, this, TimerNotificationService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    // Calculate the time when it expires.
    long wakeupTime = System.currentTimeMillis() + duration;

    // Schedule an alarm.
    alarm.setExact(AlarmManager.RTC_WAKEUP, wakeupTime, pendingIntent);
}

From source file:org.wso2.emm.agent.services.DeviceStartupIntentReceiver.java

/**
 * Initiates device notifier on device startup.
 * @param context - Application context.
 *///from   ww  w  .ja v a  2  s. c  o  m
private void setRecurringAlarm(Context context) {
    this.resources = context.getApplicationContext().getResources();
    String mode = Preference.getString(context, Constants.PreferenceFlag.NOTIFIER_TYPE);
    boolean isLocked = Preference.getBoolean(context, Constants.IS_LOCKED);
    String lockMessage = Preference.getString(context, Constants.LOCK_MESSAGE);

    if (lockMessage == null || lockMessage.isEmpty()) {
        lockMessage = resources.getString(R.string.txt_lock_activity);
    }

    if (isLocked) {
        Operation lockOperation = new Operation();
        lockOperation.setId(DEFAULT_ID);
        lockOperation.setCode(Constants.Operation.DEVICE_LOCK);
        try {
            JSONObject payload = new JSONObject();
            payload.put(Constants.ADMIN_MESSAGE, lockMessage);
            payload.put(Constants.IS_HARD_LOCK_ENABLED, true);
            lockOperation.setPayLoad(payload.toString());
            OperationProcessor operationProcessor = new OperationProcessor(context);
            operationProcessor.doTask(lockOperation);
        } catch (AndroidAgentException e) {
            Log.e(TAG, "Error occurred while executing hard lock operation at the device startup");
        } catch (JSONException e) {
            Log.e(TAG, "Error occurred while building hard lock operation payload");
        }
    }

    int interval = Preference.getInt(context, context.getResources().getString(R.string.shared_pref_frequency));
    if (interval == DEFAULT_INDEX) {
        interval = DEFAULT_INTERVAL;
    }

    if (mode == null) {
        mode = Constants.NOTIFIER_LOCAL;
    }

    if (Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED)
            && Constants.NOTIFIER_LOCAL.equals(mode.trim().toUpperCase(Locale.ENGLISH))) {
        long startTime = DEFAULT_TIME_MILLISECONDS;

        Intent alarmIntent = new Intent(context, AlarmReceiver.class);
        PendingIntent recurringAlarmIntent = PendingIntent.getBroadcast(context, DEFAULT_REQUEST_CODE,
                alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, startTime, interval,
                recurringAlarmIntent);
        Log.d(TAG, "Setting up alarm manager for polling every " + interval + " milliseconds.");
    }
}