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.drinviewer.droiddrinviewer.DrinViewerBroadcastReceiver.java

/**
 * Starts the alarm repeater after a disconnection from a WiFi network.
 * The alarm is firing request to discover server at regular time interval
 * /*from   w ww  .  j  a  v  a 2  s.  c om*/
 * @param context The context to use
 * @return true on success
 */
private boolean startAlarmRepeater(Context context) {

    boolean returnValue = false;

    // Gets the Binder to the DiscoverServerService
    IBinder b = peekService(context, new Intent(context, DiscoverServerService.class));
    DiscoverServerApi discoverServerApi = DiscoverServerApi.Stub.asInterface(b);

    // start the alarm repeater only if the api exists and the discover process in not running
    try {
        if (b != null && discoverServerApi != null && !discoverServerApi.isRunning()) {
            // Get the alarm manager
            if (alarmManager == null)
                alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            // Instantiate the intent and set its action
            Intent i = new Intent(context, this.getClass());
            i.setAction(context.getResources().getString(R.string.broadcast_startdiscovery));
            // send the wifiBroadcastAddress together with the intent
            i.putExtra("wifiBroadcastAddress", wifiBroadcastAddress);
            // Get the broadcast
            PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            if (pending != null) {
                Calendar cal = Calendar.getInstance();
                // cancel the alarm
                alarmManager.cancel(pending);
                // Run the intent immediately and schedule repeating at fixed time intervals
                context.sendBroadcast(i);
                alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                        cal.getTimeInMillis() + DroidDrinViewerConstants.DISCOVER_REPEAT_TIME,
                        DroidDrinViewerConstants.DISCOVER_REPEAT_TIME, pending);
                returnValue = true;
            }
        }
    } catch (RemoteException e) {
        e.printStackTrace();
        returnValue = false;
    }
    return returnValue;
}

From source file:com.chaitu.lmscalendar.ui.UrlDialog.java

@Override
public void onStart() {
    super.onStart();
    final AlertDialog dlg = (AlertDialog) getDialog();
    if (dlg == null)
        return;//  ww w. j  a  v  a 2  s .  co m

    View.OnClickListener onClickTask;
    onClickTask = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String url = mTextCalendarUrl.getText().toString();
            String username = mTextUsername.getText().toString();
            String password = mTextPassword.getText().toString();
            String calendar = mTextPassword.getText().toString();
            long sync_interval = mSpinnerSyncInterval.getSelectedItemId();
            CalendarModel calendarModel = (CalendarModel) mSpinnerCalendar.getSelectedItem();
            int calID = calendarModel.getId();
            String calName = calendarModel.getName();

            /*if (!mActivity.setSource(url, null, username, password)) {
            TextView label = (TextView) dlg.findViewById(R.id.TextViewUrlError);
            label.setText(R.string.invalid_url);
            return;
            }*/

            Intent intent = new Intent(getActivity(), AlarmReceiver.class);
            intent.putExtra(AlarmReceiver.ACTION_ALARM, AlarmReceiver.ACTION_ALARM);
            final PendingIntent pIntent = PendingIntent.getBroadcast(getActivity(), 1234567, intent,
                    PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarms = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
            alarms.cancel(pIntent);

            Settings settings = mActivity.getSettings();
            settings.putString(Settings.PREF_LASTURL, url);

            settings.putString(Settings.PREF_LASTURLUSERNAME, username);
            settings.putString(Settings.PREF_LASTURLPASSWORD, password);
            settings.putString(Settings.PREF_LASTCALENDARNAME, calName);
            settings.putInt(Settings.PREF_LASTCALENDARID, calID);
            settings.putInt(Settings.PREF_LASTSYNCINTERVAL, (int) sync_interval);
            mActivity.startIntent();
            dlg.dismiss();

        }
    };

    dlg.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(onClickTask);

}

From source file:org.leopub.mat.service.MessageService.java

public static void setUpdate(int latency, int period) {
    Context context = MyApplication.getAppContext();
    Logger.i(TAG, "setUpdate latency:" + latency + ", period:" + period);
    Intent i = new Intent(context, MessageService.class);
    PendingIntent pi = PendingIntent.getService(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

    if (period > 0) {
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + latency * 60 * 1000,
                period * 60 * 1000, pi);
    } else {// w w w . j av  a 2  s .  c o  m
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + latency * 60 * 1000, pi);
    }
    Logger.i(TAG, "setUpdate Done");
}

From source file:com.ayogo.cordova.notification.ScheduledNotificationManager.java

public ScheduledNotification cancelNotification(String tag) {
    LOG.v(NotificationPlugin.TAG, "cancelNotification: " + tag);
    SharedPreferences prefs = getPrefs();
    SharedPreferences.Editor editor = prefs.edit();

    Map<String, ?> notifications = prefs.getAll();
    ScheduledNotification notification = null;

    for (String key : notifications.keySet()) {
        try {// w ww. j  ava2 s.c o  m
            JSONObject value = new JSONObject(notifications.get(key).toString());
            String ntag = value.optString("tag");
            LOG.v(NotificationPlugin.TAG, "checking Notification: " + value.toString());
            if (ntag != null && ntag.equals(tag)) {
                LOG.v(NotificationPlugin.TAG, "found Notification: " + value.toString());
                notification = new ScheduledNotification(value.optString("title", null), value);

                editor.remove(key);

                LOG.v(NotificationPlugin.TAG, "unscheduling Notification: ");
                //unschedule the alarm
                Intent intent = new Intent(context, TriggerReceiver.class);
                intent.setAction(ntag);

                PendingIntent pi = PendingIntent.getBroadcast(context, INTENT_REQUEST_CODE, intent,
                        PendingIntent.FLAG_CANCEL_CURRENT);

                AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
                alarmManager.cancel(pi);
            }
        } catch (JSONException e) {
        }
    }

    editor.commit();

    if (notification != null) {
        LOG.v(NotificationPlugin.TAG, "returning Notification " + notification.toString());
    } else {
        LOG.v(NotificationPlugin.TAG, "could not find Notification " + tag);
    }

    return notification;
}

From source file:com.android.deskclock.data.TimerNotificationBuilderPreN.java

@Override
public Notification build(Context context, NotificationModel nm, List<Timer> unexpired) {
    final Timer timer = unexpired.get(0);
    final long remainingTime = timer.getRemainingTime();

    // Generate some descriptive text, a title, and some actions based on timer states.
    final String contentText;
    final String contentTitle;
    @DrawableRes//from  w ww.j  a  v a  2  s  .  c  o m
    int firstActionIconId, secondActionIconId = 0;
    @StringRes
    int firstActionTitleId, secondActionTitleId = 0;
    Intent firstActionIntent, secondActionIntent = null;

    if (unexpired.size() == 1) {
        contentText = formatElapsedTimeUntilExpiry(context, remainingTime);

        if (timer.isRunning()) {
            // Single timer is running.
            if (TextUtils.isEmpty(timer.getLabel())) {
                contentTitle = context.getString(R.string.timer_notification_label);
            } else {
                contentTitle = timer.getLabel();
            }

            firstActionIconId = R.drawable.ic_pause_24dp;
            firstActionTitleId = R.string.timer_pause;
            firstActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_PAUSE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_add_24dp;
            secondActionTitleId = R.string.timer_plus_1_min;
            secondActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_ADD_MINUTE_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        } else {
            // Single timer is paused.
            contentTitle = context.getString(R.string.timer_paused);

            firstActionIconId = R.drawable.ic_start_24dp;
            firstActionTitleId = R.string.sw_resume_button;
            firstActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_START_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());

            secondActionIconId = R.drawable.ic_reset_24dp;
            secondActionTitleId = R.string.sw_reset_button;
            secondActionIntent = new Intent(context, TimerService.class)
                    .setAction(HandleDeskClockApiCalls.ACTION_RESET_TIMER)
                    .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId());
        }
    } else {
        if (timer.isRunning()) {
            // At least one timer is running.
            final String timeRemaining = formatElapsedTimeUntilExpiry(context, remainingTime);
            contentText = context.getString(R.string.next_timer_notif, timeRemaining);
            contentTitle = context.getString(R.string.timers_in_use, unexpired.size());
        } else {
            // All timers are paused.
            contentText = context.getString(R.string.all_timers_stopped_notif);
            contentTitle = context.getString(R.string.timers_stopped, unexpired.size());
        }

        firstActionIconId = R.drawable.ic_reset_24dp;
        firstActionTitleId = R.string.timer_reset_all;
        firstActionIntent = TimerService.createResetUnexpiredTimersIntent(context);
    }

    // Intent to load the app and show the timer when the notification is tapped.
    final Intent showApp = new Intent(context, HandleDeskClockApiCalls.class)
            .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK).setAction(HandleDeskClockApiCalls.ACTION_SHOW_TIMERS)
            .putExtra(HandleDeskClockApiCalls.EXTRA_TIMER_ID, timer.getId())
            .putExtra(HandleDeskClockApiCalls.EXTRA_EVENT_LABEL, R.string.label_notification);

    final PendingIntent pendingShowApp = PendingIntent.getActivity(context, 0, showApp,
            PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setOngoing(true)
            .setLocalOnly(true).setShowWhen(false).setAutoCancel(false).setContentText(contentText)
            .setContentTitle(contentTitle).setContentIntent(pendingShowApp)
            .setSmallIcon(R.drawable.stat_notify_timer).setPriority(NotificationCompat.PRIORITY_HIGH)
            .setCategory(NotificationCompat.CATEGORY_ALARM).setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
            .setColor(ContextCompat.getColor(context, R.color.default_background));

    final PendingIntent action1 = Utils.pendingServiceIntent(context, firstActionIntent);
    final String action1Title = context.getString(firstActionTitleId);
    builder.addAction(firstActionIconId, action1Title, action1);

    if (secondActionIntent != null) {
        final PendingIntent action2 = Utils.pendingServiceIntent(context, secondActionIntent);
        final String action2Title = context.getString(secondActionTitleId);
        builder.addAction(secondActionIconId, action2Title, action2);
    }

    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    final Intent updateNotification = TimerService.createUpdateNotificationIntent(context);
    if (timer.isRunning() && remainingTime > MINUTE_IN_MILLIS) {
        // Schedule a callback to update the time-sensitive information of the running timer.
        final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_UPDATE_CURRENT);

        final long nextMinuteChange = remainingTime % MINUTE_IN_MILLIS;
        final long triggerTime = SystemClock.elapsedRealtime() + nextMinuteChange;
        TimerModel.schedulePendingIntent(am, triggerTime, pi);
    } else {
        // Cancel the update notification callback.
        final PendingIntent pi = PendingIntent.getService(context, 0, updateNotification,
                PendingIntent.FLAG_ONE_SHOT | PendingIntent.FLAG_NO_CREATE);
        if (pi != null) {
            am.cancel(pi);
            pi.cancel();
        }
    }

    return builder.build();
}

From source file:com.groundupworks.wings.core.WingsService.java

/**
 * Schedules an alarm to start the {@link WingsService}.
 *
 * @param context the {@link Context}./*from  ww w  .ja  v  a 2s  .  c  o m*/
 * @param delay   how far in the future to schedule the alarm.
 */
static void scheduleWingsService(Context context, long delay) {
    Context appContext = context.getApplicationContext();

    // Create pending intent.
    Intent intent = new Intent(appContext, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(appContext, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Set alarm.
    AlarmManager alarmManager = (AlarmManager) appContext.getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC_WAKEUP, delay, pendingIntent);
}

From source file:com.aafr.alfonso.sunshine.app.ForecastFragment.java

private void updateWeather() {
    Intent alarmIntent = new Intent(getActivity(), SunshineService.AlarmReceiver.class);
    alarmIntent.putExtra(SunshineService.LOCATION_QUERY_EXTRA, Utility.getPreferredLocation(getActivity()));

    //Wrap in a pending intent which only fires once.
    PendingIntent pi = PendingIntent.getBroadcast(getActivity(), 0, alarmIntent, PendingIntent.FLAG_ONE_SHOT);//getBroadcast(context, 0, i, 0);

    AlarmManager am = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);

    //Set the AlarmManager to wake up the system.
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, pi);
}

From source file:com.jay.pea.mhealthapp2.utilityClasses.AlarmReceiver.java

public void CancelAlarm(Context context) {
    Intent intent = new Intent(context, AlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    alarmManager.cancel(sender);//www . j  a  va 2 s  .co m
}

From source file:org.sirimangalo.meditationplus.ActivityMain.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);

    context = this;

    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    postTask = new PostTaskRunner(postHandler, this);

    // Create a new service client and bind our activity to this service
    scheduleClient = new ScheduleClient(this);
    scheduleClient.doBindService();/*from w w  w  . java2  s.  c om*/

    mAlarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    mNM = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    setContentView(R.layout.activity_main);

    onlineList = (TextView) findViewById(R.id.online);

    resultReceiver = new MyResultReceiver(null);

    // loading dialog
    loadingDialog = new ProgressDialog(this);
    loadingDialog.setTitle(R.string.processing);

    // Set up the action bar.
    final ActionBar actionBar = getSupportActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab. We can also use ActionBar.Tab#select() to do this if we have
    // a reference to the Tab.
    mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {

            // close keyboard

            View view = getCurrentFocus();
            if (view != null) {
                inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }

            // reset chat title

            if (position == 1 && newChats) {
                if (actionBar.getTabAt(1) != null)
                    actionBar.getTabAt(1)
                            .setText(getString(R.string.title_section2).toUpperCase(Locale.getDefault()));
                newChats = false;
            }

            currentPosition = position;
            actionBar.setSelectedNavigationItem(position);
        }
    });
    mViewPager.setOffscreenPageLimit(2);

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        // Create a tab with text corresponding to the page title defined by
        // the adapter. Also specify this Activity object, which implements
        // the TabListener interface, as the callback (listener) for when
        // this tab is selected.
        actionBar
                .addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
    }
    username = prefs.getString("username", "");
    loginToken = prefs.getString("login_token", "");
    if (loginToken.equals(""))
        showLogin();

}

From source file:com.fanfou.app.opensource.service.DownloadService.java

public static void unset(final Context context) {
    final AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.cancel(DownloadService.getPendingIntent(context));
    if (AppContext.DEBUG) {
        Log.d(DownloadService.TAG, "unset");
    }//from   w  w w .  java  2s.  c o m
}