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:org.pixmob.freemobile.netstat.MonitorService.java

private void ensureServiceStaysRunning() {
    // KitKat appears to have (in some cases) forgotten how to honor START_STICKY
    // and if the service is killed, it doesn't restart.  On an emulator & AOSP device, it restarts...
    // on my CM device, it does not - WTF?  So, we'll make sure it gets back
    // up and running in a minimum of 10 minutes.  We reset our timer on a handler every
    // 2 minutes...but since the handler runs on uptime vs. the alarm which is on realtime,
    // it is entirely possible that the alarm doesn't get reset.  So - we make it a noop,
    // but this will still count against the app as a wakelock when it triggers.  Oh well,
    // it should never cause a device wakeup.  We're also at SDK 19 preferred, so the alarm
    // mgr set algorithm is better on memory consumption which is good.
    // http://stackoverflow.com/a/20735519/1527491
    if (prefs.getBoolean(SP_KEY_ENABLE_AUTO_RESTART_SERVICE, false) && Arrays
            .asList(ANDROID_VERSIONS_ALLOWED_TO_AUTO_RESTART_SERVICE).contains(Build.VERSION.RELEASE)) {
        if (DEBUG)
            Log.d(TAG, "ensureServiceStaysRunning > setting alarm. [ Kitkat START_STICKY bug ]");
        // A restart intent - this never changes...        
        final int restartAlarmInterval = 10 * 60 * 1000;
        final int resetAlarmTimer = 1 * 60 * 1000;
        final Intent restartIntent = new Intent(this, MonitorService.class);
        restartIntent.putExtra(INTENT_ALARM_RESTART_SERVICE_DIED, true);
        final AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Handler restartServiceHandler = new Handler() {
            @Override//from  w ww.  j  a v  a  2  s  . co  m
            public void handleMessage(Message msg) {
                // Create a pending intent
                PendingIntent pintent = PendingIntent.getService(getApplicationContext(), 0, restartIntent, 0);
                alarmMgr.set(AlarmManager.ELAPSED_REALTIME,
                        SystemClock.elapsedRealtime() + restartAlarmInterval, pintent);
                sendEmptyMessageDelayed(0, resetAlarmTimer);
            }
        };
        restartServiceHandler.sendEmptyMessageDelayed(0, 0);
    }
}

From source file:com.andrew.apollo.MusicPlaybackService.java

private void initService() {
    // Initialize the favorites and recents databases
    mFavoritesCache = FavoritesStore.getInstance(this);
    mRecentsCache = RecentStore.getInstance(this);

    // Initialize the notification helper
    mNotificationHelper = new NotificationHelper(this);

    // Initialize the image fetcher
    mImageFetcher = ImageFetcher.getInstance(this);
    // Initialize the image cache
    mImageFetcher.setImageCache(ImageCache.getInstance(this));

    // Start up the thread running the service. Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block. We also make it
    // background priority so CPU-intensive work will not disrupt the UI.
    final HandlerThread thread = new HandlerThread("MusicPlayerHandler",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();/*from  w ww.j  a v a2 s  . c  o m*/

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, thread.getLooper());

    // Initialize the audio manager and register any headset controls for
    // playback
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    try {
        if (mAudioManager != null) {
            mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);
        }
    } catch (SecurityException e) {
        e.printStackTrace();
        // ignore
        // some times the phone does not grant the MODIFY_PHONE_STATE permission
        // this permission is for OMEs and we can't do anything about it
    }

    // Use the remote control APIs to set the playback state
    setUpRemoteControlClient();

    // Initialize the preferences
    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    ConfigurationManager CM = ConfigurationManager.instance();
    // Load Repeat Mode
    setRepeatMode(CM.getInt(Constants.PREF_KEY_GUI_PLAYER_REPEAT_MODE));
    // Load Shuffle Mode On/Off
    enableShuffle(CM.getBoolean(Constants.PREF_KEY_GUI_PLAYER_SHUFFLE_ENABLED));
    MusicUtils.isShuffleEnabled();

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Initialize the wake lock
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
    if (powerManager != null) {
        mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, getClass().getName());
        mWakeLock.setReferenceCounted(false);
    }
    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN_ACTION);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    // Listen for the idle state
    scheduleDelayedShutdown();

    // Bring the queue back
    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
    updateNotification();
}

From source file:com.notalenthack.blaster.CommandActivity.java

private void cancelStatusUpdate() {
    // Setup expiration if we never get a message from the service
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent();
    intent.setAction(Constants.ACTION_REFRESH_STATUS);
    PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    am.cancel(pi);/*from   w w  w.j ava2  s.c om*/
}

From source file:ca.ualberta.cs.drivr.MainActivity.java

private void setNotificationAlarm(Context context) {
    Log.d("ME", "Alarm setup");
    Intent intent = new Intent(getApplicationContext(), NotificationReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

    AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    am.cancel(pendingIntent);//from   ww  w .ja  va  2s  .com
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000, pendingIntent);
    Log.d("ME", "Alarm started");
}

From source file:de.ub0r.android.websms.WebSMSReceiver.java

/**
 * Schedules resend of a message.//from   w  w w . ja  v  a 2  s  .c o  m
 *
 * @param context context
 * @param specs   {@link de.ub0r.android.websms.connector.common.ConnectorSpec}
 * @param command {@link de.ub0r.android.websms.connector.common.ConnectorCommand}
 */
private static void scheduleMessageResend(final Context context, final ConnectorSpec specs,
        final ConnectorCommand command) {

    long msgId = command.getMsgId();

    final Intent resendIntent = new Intent(Connector.ACTION_RESEND);
    command.setToIntent(resendIntent);
    specs.setToIntent(resendIntent);

    AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + RESEND_DELAY_MS,
            PendingIntent.getBroadcast(context, (int) msgId, resendIntent, PendingIntent.FLAG_CANCEL_CURRENT));
}

From source file:com.pacoapp.paco.triggering.NotificationCreator.java

@SuppressLint("NewApi")
private void createAlarmToCancelNotificationAtTimeout(Context context, NotificationHolder notificationHolder) {
    DateTime alarmTime = new DateTime(notificationHolder.getAlarmTime());
    int timeoutMinutes = (int) (notificationHolder.getTimeoutMillis() / MILLIS_IN_MINUTE);
    DateTime timeoutTime = new DateTime(alarmTime).plusMinutes(timeoutMinutes);
    long elapsedDurationInMillis = timeoutTime.getMillis();

    Log.info("Creating cancel alarm to timeout notification for holder: " + notificationHolder.getId()
            + ". experiment = " + notificationHolder.getExperimentId() + ". alarmtime = "
            + new DateTime(alarmTime).toString() + " timing out in " + timeoutMinutes + " minutes");

    Intent ultimateIntent = new Intent(context, AlarmReceiver.class);
    Uri uri = Uri.withAppendedPath(NotificationHolderColumns.CONTENT_URI,
            notificationHolder.getId().toString());
    ultimateIntent.setData(uri);//w w  w .jav  a 2  s.c om
    ultimateIntent.putExtra(NOTIFICATION_ID, notificationHolder.getId().longValue());

    PendingIntent intent = PendingIntent.getBroadcast(context.getApplicationContext(), 2, ultimateIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(intent);
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
    }

}

From source file:org.vshgap.android.NotificationsController.java

private void scheduleNotificationDelay(boolean onlineReason) {
    try {//ww  w.j a v a 2 s .  c o m
        FileLog.e("tmessages", "delay notification start, onlineReason = " + onlineReason);
        AlarmManager alarm = (AlarmManager) ApplicationLoader.applicationContext
                .getSystemService(Context.ALARM_SERVICE);
        PendingIntent pintent = PendingIntent.getService(ApplicationLoader.applicationContext, 0,
                new Intent(ApplicationLoader.applicationContext, NotificationDelay.class), 0);
        SharedPreferences preferences = ApplicationLoader.applicationContext
                .getSharedPreferences("Notifications", Activity.MODE_PRIVATE);
        if (onlineReason) {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 3 * 1000, pintent);
        } else {
            alarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000, pintent);
        }
    } catch (Exception e) {
        FileLog.e("tmessages", e);
    }
}

From source file:me.tatarka.support.internal.job.JobStore.java

private void markForBootSession(JobStatus jobStatus) {
    // Pending intents are cleared on reboot. Therefore, we can use one to mark that we haven't
    // rebooted yet.
    Intent intent = new Intent(mContext, JobSchedulerService.class).setAction(jobStatus.toShortString());
    PendingIntent pendingIntent = PendingIntent.getService(mContext, jobStatus.getJobId(), intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    // Have the alarm manager hold on to our pending intent so it will still be there even if our app is killed.
    AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.ELAPSED_REALTIME, Long.MAX_VALUE, pendingIntent);
}

From source file:com.cyanogenmod.eleven.MusicPlaybackService.java

/**
 * {@inheritDoc}/* w  w  w  .j  a  v a 2  s . c om*/
 */
@Override
public void onCreate() {
    if (D)
        Log.d(TAG, "Creating service");
    super.onCreate();

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Initialize the favorites and recents databases
    mRecentsCache = RecentStore.getInstance(this);

    // gets the song play count cache
    mSongPlayCountCache = SongPlayCount.getInstance(this);

    // gets a pointer to the playback state store
    mPlaybackStateStore = MusicPlaybackState.getInstance(this);

    // Initialize the image fetcher
    mImageFetcher = ImageFetcher.getInstance(this);
    // Initialize the image cache
    mImageFetcher.setImageCache(ImageCache.getInstance(this));

    // Start up the thread running the service. Note that we create a
    // separate thread because the service normally runs in the process's
    // main thread, which we don't want to block. We also make it
    // background priority so CPU-intensive work will not disrupt the UI.
    mHandlerThread = new HandlerThread("MusicPlayerHandler", android.os.Process.THREAD_PRIORITY_BACKGROUND);
    mHandlerThread.start();

    // Initialize the handler
    mPlayerHandler = new MusicPlayerHandler(this, mHandlerThread.getLooper());

    // Initialize the audio manager and register any headset controls for
    // playback
    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    mMediaButtonReceiverComponent = new ComponentName(getPackageName(),
            MediaButtonIntentReceiver.class.getName());
    mAudioManager.registerMediaButtonEventReceiver(mMediaButtonReceiverComponent);

    // Use the remote control APIs to set the playback state
    setUpMediaSession();

    // Initialize the preferences
    mPreferences = getSharedPreferences("Service", 0);
    mCardId = getCardId();

    registerExternalStorageListener();

    // Initialize the media player
    mPlayer = new MultiPlayer(this);
    mPlayer.setHandler(mPlayerHandler);

    // Initialize the intent filter and each action
    final IntentFilter filter = new IntentFilter();
    filter.addAction(SERVICECMD);
    filter.addAction(TOGGLEPAUSE_ACTION);
    filter.addAction(PAUSE_ACTION);
    filter.addAction(STOP_ACTION);
    filter.addAction(NEXT_ACTION);
    filter.addAction(PREVIOUS_ACTION);
    filter.addAction(PREVIOUS_FORCE_ACTION);
    filter.addAction(REPEAT_ACTION);
    filter.addAction(SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

    // Get events when MediaStore content changes
    mMediaStoreObserver = new MediaStoreObserver(mPlayerHandler);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);
    getContentResolver().registerContentObserver(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, true,
            mMediaStoreObserver);

    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicPlaybackService.class);
    shutdownIntent.setAction(SHUTDOWN);

    mAlarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mShutdownIntent = PendingIntent.getService(this, 0, shutdownIntent, 0);

    // Listen for the idle state
    scheduleDelayedShutdown();

    // Bring the queue back
    reloadQueue();
    notifyChange(QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:me.tatarka.support.internal.job.JobStore.java

private void unmarkForBootSession(JobStatus jobStatus) {
    Intent intent = new Intent(mContext, JobSchedulerService.class).setAction(jobStatus.toShortString());
    PendingIntent pendingIntent = PendingIntent.getService(mContext, jobStatus.getJobId(), intent,
            PendingIntent.FLAG_NO_CREATE);
    if (pendingIntent != null) {
        AlarmManager am = (AlarmManager) mContext.getSystemService(Context.ALARM_SERVICE);
        am.cancel(pendingIntent);/*from   www . j a v  a 2  s  .  c om*/
        pendingIntent.cancel();
    }
}