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.dogar.geodesic.map.MainActivity.java

private void restartApp() {
    Intent mStartActivity = new Intent(this, MainActivity.class);
    int mPendingIntentId = 123456;
    PendingIntent mPendingIntent = PendingIntent.getActivity(this, mPendingIntentId, mStartActivity,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager mgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mPendingIntent);
    System.exit(0);/*  w  w  w  .  j a v  a  2s .  c o  m*/
}

From source file:no.firestorm.weathernotificatonservice.WeatherNotificationService.java

/**
 * Set alarm//from   w ww.  j a va  2 s.  com
 * 
 * @param updateRate
 *            in minutes
 */
private void setAlarm(long updateRate) {
    // Set alarm
    final PendingIntent pendingIntent = PendingIntent.getService(this, 0,
            new Intent(this, WeatherNotificationService.class), PendingIntent.FLAG_UPDATE_CURRENT);
    final AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    // Set time to next hour plus 5 minutes:
    final long now = System.currentTimeMillis();
    long triggerAtTime = now;
    // set back to last hour plus 2 minutes:
    triggerAtTime -= triggerAtTime % 3600000 - 12000;
    // Add selected update rate
    triggerAtTime += updateRate * 60000;

    // Check that trigger time is not passed.
    if (triggerAtTime < now)
        triggerAtTime = now + updateRate * 60000;

    alarm.set(AlarmManager.RTC, triggerAtTime, pendingIntent);
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static long setUpdateAlarm(Context context, boolean initial) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    Intent alarmintent = new Intent(context, AlarmReceiver.class);
    alarmintent.setAction(AlarmReceiver.ALARM_UPDATE);

    PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, alarmintent, 0);

    MyApp.LogDebug(LOG_TAG, "set update alarm");
    long next_fetch;
    long interval;
    Time t = new Time();
    t.setToNow();//from w  ww.java  2  s  .  c  o  m
    long now = t.toMillis(true);

    if ((now >= MyApp.first_day_start) && (now < MyApp.last_day_end)) {
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        next_fetch = now + interval;
    } else if (now >= MyApp.last_day_end) {
        MyApp.LogDebug(LOG_TAG, "cancel alarm post congress");
        alarmManager.cancel(pendingintent);
        return 0;
    } else {
        interval = AlarmManager.INTERVAL_DAY;
        next_fetch = now + interval;
    }

    if ((now < MyApp.first_day_start) && ((now + AlarmManager.INTERVAL_DAY) >= MyApp.first_day_start)) {
        next_fetch = MyApp.first_day_start;
        interval = 2 * AlarmManager.INTERVAL_HOUR;
        if (!initial) {
            MyApp.LogDebug(LOG_TAG, "update alarm to interval " + interval + ", next in " + (next_fetch - now));
            alarmManager.cancel(pendingintent);
            alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
        }
    }

    if (initial) {
        MyApp.LogDebug(LOG_TAG,
                "set initial alarm to interval " + interval + ", next in " + (next_fetch - now));
        alarmManager.cancel(pendingintent);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next_fetch, interval, pendingintent);
    }

    return interval;
}

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

public void setupAlarm(int hourOfDay) {
    //Alarm has been called
    ALARM_NOT_CALLED = false;/*from  w ww . ja  v  a 2s.  c  o m*/

    //Setup what the alarm has to do when it goes off.
    Intent alarmIntent = new Intent(SmogMapActivity.this, AirAzureDownloadService.AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(SmogMapActivity.this, 0, alarmIntent,
            PendingIntent.FLAG_ONE_SHOT);//getBroadcast(context, 0, i, 0);
    Log.v("OnCreate", "Alarm Intent Created");

    //Set the AlarmManager to wake up the system every day at 6 a.m.
    AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
    long timeEveryDay = calendar.getTimeInMillis();
    long currentTime = System.currentTimeMillis();
    long oneMin = 60 * 1000;
    am.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeEveryDay, AlarmManager.INTERVAL_DAY, pi);
    if ((currentTime + oneMin) < timeEveryDay) {
        Log.v(LOG_TAG, "First time download and time is before 6 a.m.");
        Intent firstTimeDownloadIntent = new Intent(getApplicationContext(), AirAzureDownloadService.class);
        startService(firstTimeDownloadIntent);
    }
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Disables alert in AlarmManger and StatusBar.
 *
 * @param id Alarm ID./*from w ww.ja  v  a2s .  c  o  m*/
 */
static void disableAlert(Context context) {
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, new Intent(ALARM_ALERT_ACTION),
            PendingIntent.FLAG_CANCEL_CURRENT);
    am.cancel(sender);
    setStatusBarIcon(context, false);
    saveNextAlarm(context, "");
}

From source file:com.google.android.apps.paco.NotificationCreator.java

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.i(PacoConstants.TAG,//from w w w.j av  a 2  s  .c o  m
            "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);
    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);
    alarmManager.set(AlarmManager.RTC_WAKEUP, elapsedDurationInMillis, intent);
}

From source file:com.example.feedback.ActivityFeedback.java

/**
 * Set broadcast receiver of type FeedbackBroadcastReceiver and create an alarm to test internet
 * connection repeatedly until feedback is sent.
 *
 * @param   context  application context of calling activity
 *///from   w  ww  .j av a2 s. c o m
public void setAlarm(Context context) {
    intent = new Intent(this, FeedbackBroadcastReceiver.class);
    pending = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pending);
    // Set alarm to start immediately and repeat every fifteen minutes, approximately.
    alarm.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
            AlarmManager.INTERVAL_FIFTEEN_MINUTES, pending);
}

From source file:cw.kop.autobackground.LiveWallpaperService.java

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

    handler = new Handler();
    prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    AppSettings.initPrefs(prefs, getApplicationContext());

    AppSettings.resetVer1_30();/*from www .ja  va  2 s .  co  m*/
    AppSettings.resetVer1_40();
    AppSettings.resetVer2_00();
    AppSettings.resetVer2_00_20();

    setIntents();
    createGameIntents();

    registerReceiver(serviceReceiver, getServiceIntentFilter());
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    startAlarms();

    if (AppSettings.useNotification()) {
        startNotification(true);
    }

    googleApiClient = new GoogleApiClient.Builder(getApplicationContext())
            .addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {
                @Override
                public void onConnected(Bundle connectionHint) {
                    isWearConnected = true;
                    if (AppSettings.useToast()) {
                        Toast.makeText(LiveWallpaperService.this, "Connected to Wear device", Toast.LENGTH_LONG)
                                .show();
                    }
                }

                @Override
                public void onConnectionSuspended(int cause) {
                    isWearConnected = false;
                }
            }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult result) {
                    isWearConnected = false;
                }
            })
            // Request access only to the Wearable API
            .addApi(Wearable.API).build();
    googleApiClient.connect();

    Log.i(TAG, "onCreateService");
}

From source file:com.koma.music.service.MusicService.java

/**
 * {@inheritDoc}//www  . ja  va  2s  .  co  m
 */
@Override
public void onCreate() {
    LogUtils.d(TAG, "Creating service");
    super.onCreate();

    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        stopSelf();
        return;
    } else {
        mReadGranted = true;
    }

    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Initialize the favorites and recents databases
    mRecentlyPlayCache = RecentlyPlay.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);

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

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

    mShowAlbumArtOnLockscreen = mPreferences.getBoolean(PreferenceUtils.SHOW_ALBUM_ART_ON_LOCKSCREEN, false);
    setShakeToPlayEnabled(mPreferences.getBoolean(PreferenceUtils.SHAKE_TO_PLAY, false));

    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(MusicServiceConstants.SERVICECMD);
    filter.addAction(MusicServiceConstants.TOGGLEPAUSE_ACTION);
    filter.addAction(MusicServiceConstants.PAUSE_ACTION);
    filter.addAction(MusicServiceConstants.STOP_ACTION);
    filter.addAction(MusicServiceConstants.NEXT_ACTION);
    filter.addAction(MusicServiceConstants.PREVIOUS_ACTION);
    filter.addAction(MusicServiceConstants.PREVIOUS_FORCE_ACTION);
    filter.addAction(MusicServiceConstants.REPEAT_ACTION);
    filter.addAction(MusicServiceConstants.SHUFFLE_ACTION);
    // Attach the broadcast listener
    registerReceiver(mIntentReceiver, filter);

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

    // Initialize the delayed shutdown intent
    final Intent shutdownIntent = new Intent(this, MusicService.class);
    shutdownIntent.setAction(MusicServiceConstants.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(MusicServiceConstants.QUEUE_CHANGED);
    notifyChange(META_CHANGED);
}

From source file:com.android.launcher3.widget.DigitalAppWidgetProvider.java

/**
 * Start an alarm that fires on the next quarter hour to update the world clock city
 * day when the local time or the world city crosses midnight.
 *
 * @param context The context in which the PendingIntent should perform the broadcast.
 *///from   ww w . jav a 2 s . c o  m
private void startAlarmOnQuarterHour(Context context) {
    if (context != null) {
        long onQuarterHour = Utils.getAlarmOnQuarterHour();
        PendingIntent quarterlyIntent = getOnQuarterHourPendingIntent(context);
        AlarmManager alarmManager = ((AlarmManager) context.getSystemService(Context.ALARM_SERVICE));
        if (Utils.isKitKatOrLater()) {
            alarmManager.setExact(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
        } else {
            alarmManager.set(AlarmManager.RTC, onQuarterHour, quarterlyIntent);
        }
    }
}