Example usage for android.app PendingIntent getService

List of usage examples for android.app PendingIntent getService

Introduction

In this page you can find the example usage for android.app PendingIntent getService.

Prototype

public static PendingIntent getService(Context context, int requestCode, @NonNull Intent intent,
        @Flags int flags) 

Source Link

Document

Retrieve a PendingIntent that will start a service, like calling Context#startService Context.startService() .

Usage

From source file:com.android.anton.pushnotificationwithgcm.GCMUtil.MyGcmListenerService.java

@Override
public void onTaskRemoved(Intent rootIntent) {
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());
    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1,
            restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);

    AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmManager.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000,
            restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

From source file:biz.bokhorst.bpt.BPTService.java

@Override
public void onConnected(Bundle arg0) {
    should = true;/*from   w ww . j  a  va  2  s  .  com*/
    sendActivity(getString(R.string.connected), -1, new Date().getTime());

    long interval = Integer.parseInt(preferences.getString(Preferences.PREF_ACTIVITYRECOGNITIONINTERVAL,
            Preferences.PREF_ACTIVITYRECOGNITIONINTERVAL_DEFAULT)) * 60L * 1000L;
    PendingIntent activityCallbackIntent = PendingIntent.getService(this, 0, new Intent(this, BPTService.class),
            PendingIntent.FLAG_UPDATE_CURRENT);
    ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(activityRecognitionClient, interval,
            activityCallbackIntent);
}

From source file:de.azapps.mirakel.reminders.ReminderAlarm.java

private static void createNotification(final Context context, final Task task) {
    Log.w(TAG, task.getName());/*from w w  w  .j av  a2s.  co m*/
    final NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    final Optional<Class<?>> main = Helpers.getMainActivity();
    if (!main.isPresent()) {
        return;
    }
    final Intent openIntent = new Intent(context, main.get());

    final Bundle withTask = new Bundle();
    withTask.putParcelable(DefinitionsHelper.EXTRA_TASK, task);
    openIntent.setAction(DefinitionsHelper.SHOW_TASK_REMINDER);
    openIntent.putExtra(DefinitionsHelper.EXTRA_TASK_REMINDER, task);
    openIntent.putExtra(String.valueOf(task.getId()), task.getId());
    openIntent.setData(Uri.parse(openIntent.toUri(Intent.URI_INTENT_SCHEME)));
    final PendingIntent pOpenIntent = PendingIntent.getActivity(context, 0, openIntent, 0);
    final Intent doneIntent = new Intent(context, TaskService.class);
    doneIntent.setAction(TaskService.TASK_DONE);
    doneIntent.putExtra(DefinitionsHelper.BUNDLE_WRAPPER, withTask);
    doneIntent.putExtra(String.valueOf(task.getId()), task.getId());
    doneIntent.setData(Uri.parse(doneIntent.toUri(Intent.URI_INTENT_SCHEME)));
    final PendingIntent pDoneIntent = PendingIntent.getService(context, 0, doneIntent, 0);
    final Intent laterIntent = new Intent(context, TaskService.class);
    laterIntent.setAction(TaskService.TASK_LATER);
    laterIntent.putExtra(DefinitionsHelper.BUNDLE_WRAPPER, withTask);
    laterIntent.putExtra(String.valueOf(task.getId()), task.getId());
    laterIntent.setData(Uri.parse(laterIntent.toUri(Intent.URI_INTENT_SCHEME)));
    final PendingIntent pLaterIntent = PendingIntent.getService(context, 0, laterIntent, 0);
    final boolean persistent = MirakelCommonPreferences.usePersistentReminders();
    // Build Notification
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
    builder.setContentTitle(context.getString(R.string.reminder_notification_title, task.getName()))
            .setContentText(task.getContent()).setSmallIcon(R.drawable.ic_mirakel)
            .setLargeIcon(Helpers.getBitmap(R.drawable.mirakel, context)).setContentIntent(pOpenIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH).setLights(Color.BLUE, 1500, 300)
            .setOngoing(persistent).setDefaults(Notification.DEFAULT_VIBRATE)
            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
            .addAction(R.drawable.ic_checkmark_holo_light,
                    context.getString(R.string.reminder_notification_done), pDoneIntent)
            .addAction(android.R.drawable.ic_menu_close_clear_cancel,
                    context.getString(R.string.reminder_notification_later), pLaterIntent);

    final NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    final String priority = ((task.getPriority() > 0) ? ("+" + task.getPriority())
            : String.valueOf(task.getPriority()));
    final CharSequence due;
    if (!task.getDue().isPresent()) {
        due = context.getString(R.string.no_date);
    } else {
        due = DateTimeHelper.formatDate(context, task.getDue());
    }
    inboxStyle.addLine(context.getString(R.string.reminder_notification_list, task.getList().getName()));
    inboxStyle.addLine(context.getString(R.string.reminder_notification_priority, priority));
    inboxStyle.addLine(context.getString(R.string.reminder_notification_due, due));
    builder.setStyle(inboxStyle);
    // Build notification
    if (!allReminders.contains(task.getId())) {
        allReminders.add(task.getId());

        nm.notify(DefinitionsHelper.NOTIF_REMINDER + (int) task.getId(), builder.build());
    }
}

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;//w  ww  . j a v a 2  s.  c  o  m
    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.example.android.synchronizednotifications.SynchronizedNotificationsFragment.java

/**
 * Builds a local-only notification for the handset. This is achieved by using
 * <code>setLocalOnly(true)</code>. If <code>withDismissal</code> is set to <code>true</code>, a
 * {@link android.app.PendingIntent} will be added to handle the dismissal of notification to
 * be able to remove the mirrored notification on the wearable.
 *//*w ww.j av a2 s .c  o  m*/
private void buildLocalOnlyNotification(String title, String content, int notificationId,
        boolean withDismissal) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getActivity());
    builder.setContentTitle(title).setContentText(content).setLocalOnly(true)
            .setSmallIcon(R.drawable.ic_launcher);

    if (withDismissal) {
        Intent dismissIntent = new Intent(Constants.ACTION_DISMISS);
        dismissIntent.putExtra(Constants.KEY_NOTIFICATION_ID, Constants.BOTH_ID);
        PendingIntent pendingIntent = PendingIntent.getService(this.getActivity(), 0, dismissIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setDeleteIntent(pendingIntent);
    }
    NotificationManagerCompat.from(this.getActivity()).notify(notificationId, builder.build());
}

From source file:com.rickendirk.rsgwijzigingen.ZoekService.java

private void setAlarmIn20Min() {
    Intent zoekIntent = new Intent(this, ZoekService.class);
    zoekIntent.putExtra("isAchtergrond", true);
    zoekIntent.addCategory("GeenWifiHerhaling"); //Categorie om andere intents cancelen te voorkomen
    PendingIntent pendingIntent = PendingIntent.getService(this, 3, zoekIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    Long in20Min = SystemClock.elapsedRealtime() + 1200000; //20Min in milisec.
    manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, in20Min, pendingIntent);
    Log.i(TAG, "Nieuw alarm gezet in 20 min");
}

From source file:com.umaps.gpslogger.GpsLoggingService.java

private void RequestActivityRecognitionUpdates() {
    GoogleApiClient.Builder builder = new GoogleApiClient.Builder(getApplicationContext())
            .addApi(ActivityRecognition.API).addConnectionCallbacks(new GoogleApiClient.ConnectionCallbacks() {

                @Override//from ww  w . j a va2 s .  c  om
                public void onConnectionSuspended(int arg) {
                }

                @Override
                public void onConnected(Bundle arg0) {
                    try {
                        Log.d(TAG, "Requesting activity recognition updates");
                        Intent intent = new Intent(getApplicationContext(), GpsLoggingService.class);
                        activityRecognitionPendingIntent = PendingIntent.getService(getApplicationContext(), 0,
                                intent, PendingIntent.FLAG_UPDATE_CURRENT);
                        ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(googleApiClient,
                                AppSettings.getMinimumSeconds() * 1000, activityRecognitionPendingIntent);
                    } catch (Throwable t) {
                        Log.w(TAG, "Can't connect to activity recognition service", t);
                    }

                }

            }).addOnConnectionFailedListener(new GoogleApiClient.OnConnectionFailedListener() {
                @Override
                public void onConnectionFailed(ConnectionResult arg0) {

                }
            });

    googleApiClient = builder.build();
    googleApiClient.connect();
}

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

private final static PendingIntent getPendingIntent(final Context context) {
    final Intent intent = new Intent(context, DownloadService.class);
    intent.putExtra(Constants.EXTRA_TYPE, DownloadService.TYPE_CHECK);
    final PendingIntent pi = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return pi;/* w  ww  .j a v a2s. c  o 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:com.securecomcode.text.service.KeyCachingService.java

@Override
public void onCreate() {
    super.onCreate();
    this.pending = PendingIntent.getService(this, 0,
            new Intent(PASSPHRASE_EXPIRED_EVENT, null, this, KeyCachingService.class), 0);

    if (TextSecurePreferences.isPasswordDisabled(this)) {
        try {/* w ww  .  j a v  a2s.  c  om*/
            MasterSecret masterSecret = MasterSecretUtil.getMasterSecret(this,
                    MasterSecretUtil.UNENCRYPTED_PASSPHRASE);
            setMasterSecret(masterSecret);
        } catch (InvalidPassphraseException e) {
            Log.w("KeyCachingService", e);
        }
    }
}