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.alchemiasoft.book.service.SuggestionService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG_LOG, "Starting a new book suggestion...");
    final ContentResolver cr = getContentResolver();
    final Cursor c = cr.query(BookDB.Book.CONTENT_URI, null, SELECTION, SELECT_NOT_OWNED, null);
    Book book = null;/*from ww  w  . j a  va  2 s .  c o  m*/
    try {
        if (c.moveToNext()) {
            book = Book.oneFrom(c);
        }
    } finally {
        c.close();
    }
    // Showing a notification if a not owned book is found
    if (book != null) {
        Log.d(TAG_LOG, "Found book that can be suggested: " + book);
        final String content = getString(R.string.content_book_suggestion, book.getTitle(), book.getAuthor());
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
                .setContentTitle(getString(R.string.title_book_suggestion)).setContentText(content);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(content));
        builder.setContentIntent(PendingIntent.getActivity(this, 0, HomeActivity.createFor(this, book),
                PendingIntent.FLAG_UPDATE_CURRENT));

        // ONLY 4 WEARABLE(s)
        final NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        // SECOND PAGE WITH BOOK DESCRIPTION
        wearableExtender
                .addPage(new NotificationCompat.Builder(this).setContentTitle(getString(R.string.description))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(book.getDescrition())).build());
        wearableExtender.setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.background));
        // ACTION TO PURCHASE A BOOK FROM A WEARABLE
        final PendingIntent purchaseIntent = PendingIntent.getService(this, 0, BookActionService.IntentBuilder
                .buy(this, book).notificationId(ID_SUGGESTION).wearableInput().build(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_buy,
                getString(R.string.action_buy), purchaseIntent).build());
        // ACTION TO ADD NOTES VIA VOICE REPLY
        final RemoteInput input = BookActionService.RemoteInputBuilder.create(this)
                .options(R.array.note_options).build();
        final PendingIntent notesIntent = PendingIntent
                .getService(
                        this, 0, BookActionService.IntentBuilder.addNote(this, book)
                                .notificationId(ID_SUGGESTION).wearableInput().build(),
                        PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_notes,
                getString(R.string.action_notes), notesIntent).addRemoteInput(input).build());
        // Finally extending the notification
        builder.extend(wearableExtender);

        // Sending the notification
        NotificationManagerCompat.from(this).notify(ID_SUGGESTION, builder.build());
    }
    // Completing the Wakeful Intent
    SuggestionReceiver.completeWakefulIntent(intent);
}

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

private void showTimerDoneNotification() {
    // Cancel the countdown notification to show the "timer done" notification.
    cancelCountdownNotification();//from  w  ww . j  a  v  a 2  s.c o m

    // Create an intent to restart a timer.
    Intent restartIntent = new Intent(Constants.ACTION_RESTART_ALARM, null, this,
            TimerNotificationService.class);
    PendingIntent pendingIntentRestart = PendingIntent.getService(this, 0, restartIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // Create notification that timer has expired.
    NotificationManagerCompat notifyMgr = NotificationManagerCompat.from(this);
    Notification notif = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_cc_alarm)
            .setContentTitle(getString(R.string.timer_done)).setContentText(getString(R.string.timer_done))
            .setUsesChronometer(true).setWhen(System.currentTimeMillis())
            .addAction(R.drawable.ic_cc_alarm, getString(R.string.timer_restart), pendingIntentRestart)
            .setLocalOnly(true).build();
    notifyMgr.notify(Constants.NOTIFICATION_TIMER_EXPIRED, notif);
}

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

public static void scheduleAccountPing(Context context, Intent intent) {
    if (Account.DEBUG)
        Log.d(TAG,/*from  w  w  w .  ja  v  a2  s  .c  om*/
                "Scheduling Account ping, starting = "
                        + new Timestamp(SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY)
                        + " interval (" + AlarmManager.INTERVAL_DAY + ")");
    PendingIntent reRegisterPendingIntent = PendingIntent.getService(context, 0, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
            SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY,
            reRegisterPendingIntent);
}

From source file:com.tbay.android.FrequentSMS.MainActivity.java

/**
 * Creates Intent if not already existing. Same intent is used for all fences.
 * @return Return the intent to call when position is within geofence
 *//*from  w  w w .  j  a  v  a2 s  .  c  o m*/
private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);

    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when
    // calling addGeofences() and removeGeofences().
    mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    return mGeofencePendingIntent;
}

From source file:com.github.sryze.wirebug.DebugStatusService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && intent.getAction() != null) {
        if (intent.getAction().equals(ACTION_UPDATE_STATUS)) {
            updateStatus();//from   w  w w.  j  av a  2  s  . co  m
            Intent updateStatusIntent = new Intent(DebugStatusService.this, DebugStatusService.class);
            updateStatusIntent.setAction(ACTION_UPDATE_STATUS);
            PendingIntent alarmPendingIntent = PendingIntent.getService(DebugStatusService.this, 0,
                    updateStatusIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            alarmManager.cancel(alarmPendingIntent);
            alarmManager.set(AlarmManager.ELAPSED_REALTIME,
                    SystemClock.elapsedRealtime() + STATUS_UPDATE_INTERVAL, alarmPendingIntent);
        } else if (intent.getAction().equals(ACTION_STOP)) {
            DebugManager.setTcpDebuggingEnabled(false);
            updateStatus();
        }
    }
    return START_STICKY;
}

From source file:com.actinarium.nagbox.service.NotificationHelper.java

private static void fireForMultipleTasks(Context context, Task[] tasks) {
    long currentTime = System.currentTimeMillis();
    final NotificationManagerCompat notifManager = NotificationManagerCompat.from(context);
    final int tasksCount = tasks.length;

    // Create a group of stacked notifications
    for (Task task : tasks) {

        // Notification action to stop the task
        Intent stopAction = new Intent(context, NagboxService.class);
        stopAction.setAction(NagboxService.ACTION_ON_NOTIFICATION_ACTION_STOP_TASK);
        stopAction.putExtra(NagboxService.EXTRA_TASK_ID, task.id);
        stopAction.putExtra(NagboxService.EXTRA_CANCEL_NOTIFICATION_ID, (int) task.id);

        // Since actions are "equal" (differ in extras only), need to use a unique "request code" (task.id will do)
        PendingIntent stopActionPI = PendingIntent.getService(context, (int) task.id, stopAction,
                PendingIntent.FLAG_UPDATE_CURRENT);

        Notification stackedItem = makeCommonBuilder(context, currentTime, task.id).setContentTitle(task.title)
                .setContentText(DateUtils.prettyPrintNagDuration(context, task.lastStartedAt, currentTime))
                .setGroup(NAG_NOTIFICATION_GROUP).addAction(R.drawable.ic_cancel,
                        context.getString(R.string.notification_action_stop), stopActionPI)
                .build();//from w  w w . jav  a 2  s .c  o  m

        // Well, let's use task IDs for their individual notifications then
        notifManager.notify((int) task.id, stackedItem);
    }

    // Summary text, reused
    final String summary = context.getResources().getQuantityString(R.plurals.notification_stacked_header,
            tasksCount, tasksCount);

    // Public summary notification
    // Since Android N already shows app name in the notification, display the summary in title
    boolean isApi24 = Build.VERSION.SDK_INT >= 24;
    Notification publicNotification = makeCommonBuilder(context, currentTime, Task.NO_ID)
            .setContentTitle(isApi24 ? summary : context.getString(R.string.app_name))
            .setContentText(isApi24 ? null : summary).setGroup(NAG_NOTIFICATION_GROUP).setGroupSummary(true)
            .build();

    // Create expanded (inbox style) for private notification.
    // If there are more than 5 tasks, enlist first 4 and add +x more
    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(summary);
    if (tasksCount <= 5) {
        for (Task task : tasks) {
            inboxStyle.addLine(makeInboxStyleLine(context, task, currentTime));
        }
    } else {
        for (int i = 0; i < 4; i++) {
            inboxStyle.addLine(makeInboxStyleLine(context, tasks[i], currentTime));
        }
        inboxStyle.addLine(context.getString(R.string.notification_stack_overflow, tasksCount - 4));
    }

    // Create private summary notification
    Notification privateNotification = makeCommonBuilder(context, currentTime, Task.NO_ID)
            .setPublicVersion(publicNotification)
            .setContentTitle(isApi24 ? summary : context.getString(R.string.app_name))
            .setContentText(isApi24 ? null : summary).setStyle(inboxStyle).setGroup(NAG_NOTIFICATION_GROUP)
            .setGroupSummary(true).build();

    notifManager.notify(NAG_NOTIFICATION_ID, privateNotification);
}

From source file:com.example.android.wearable.synchronizednotifications.PhoneActivity.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.
 *//*from  w w  w.j a  va 2 s . c o  m*/
private void buildLocalOnlyNotification(String title, String content, int notificationId,
        boolean withDismissal) {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    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, 0, dismissIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setDeleteIntent(pendingIntent);
    }
    NotificationManagerCompat.from(this).notify(notificationId, builder.build());
}

From source file:com.nextgis.maplibui.service.TileDownloadService.java

@Override
public void onCreate() {
    mNotifyManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    Bitmap largeIcon = NotificationHelper.getLargeIcon(R.drawable.ic_notification_download, getResources());

    Intent intentStop = new Intent(this, TileDownloadService.class);
    intentStop.setAction(ACTION_STOP);// w w  w  . jav a 2  s. c o  m
    PendingIntent stopService = PendingIntent.getService(this, 0, intentStop,
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setSmallIcon(R.drawable.ic_notification_download).setLargeIcon(largeIcon).setAutoCancel(false)
            .setOngoing(true)
            .addAction(android.R.drawable.ic_menu_close_clear_cancel, getString(R.string.cancel), stopService);

    mQueue = new LinkedList<>();
    mCanceled = false;
}

From source file:edu.umich.si.inteco.minuku.manager.MinukuNotificationManager.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "OnStartCommand");

    if (mNotificationManager == null) {
        mNotificationManager = (android.app.NotificationManager) getSystemService(Service.NOTIFICATION_SERVICE);
    }/*from ww  w.  j  ava  2 s  . co m*/

    AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarm.set(AlarmManager.RTC_WAKEUP,
            System.currentTimeMillis() + Constants.PROMPT_SERVICE_REPEAT_MILLISECONDS,
            PendingIntent.getService(this, 0, new Intent(this, MinukuNotificationManager.class), 0));

    Notification note = new Notification.Builder(getBaseContext())
            .setContentTitle(Constants.getInstance().getAppName())
            .setContentText(Constants.getInstance().getRunningAppDeclaration())
            .setSmallIcon(R.drawable.self_reflection).setAutoCancel(false).build();
    note.flags |= Notification.FLAG_NO_CLEAR;
    startForeground(42, note);

    checkRegisteredNotifications();

    return START_STICKY_COMPATIBILITY;
}

From source file:com.android.systemui.ReminderReceiver.java

@Override
public void onReceive(final Context context, Intent intent) {
    NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    SharedPreferences shared = context.getSharedPreferences(KEY_REMINDER_ACTION, Context.MODE_PRIVATE);

    if (intent.getBooleanExtra("clear", false)) {
        manager.cancel(NOTI_ID);/*www  . j  a v a2  s .  c  o m*/
        // User has set a new reminder but didn't clear
        // This notification until now
        if (!shared.getBoolean("updated", false)) {
            shared.edit().putBoolean("scheduled", false).commit();
            shared.edit().putInt("hours", -1).commit();
            shared.edit().putInt("minutes", -1).commit();
            shared.edit().putInt("day", -1).commit();
            shared.edit().putString("title", null).commit();
            shared.edit().putString("message", null).commit();
        }
    } else {
        String title = shared.getString("title", null);
        String message = shared.getString("message", null);
        if (title != null && message != null) {
            Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_qs_alarm_on);
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setTicker(title)
                    .setContentTitle(title).setContentText(message).setAutoCancel(false).setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_HIGH).setSmallIcon(R.drawable.ic_qs_alarm_on)
                    .setLargeIcon(bm).setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message));

            int alertMode = Settings.System.getIntForUser(context.getContentResolver(),
                    Settings.System.REMINDER_ALERT_NOTIFY, 0, UserHandle.USER_CURRENT);
            PendingIntent result = null;
            Intent serviceIntent = new Intent(context, ReminderService.class);
            if (alertMode != 0 && !QuietHoursHelper.inQuietHours(context, Settings.System.QUIET_HOURS_MUTE)) {
                context.startService(serviceIntent);
            }

            // Stop sound on click
            serviceIntent.putExtra("stopSelf", true);
            result = PendingIntent.getService(context, 1, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.setContentIntent(result);

            // Add button for dismissal
            serviceIntent.putExtra("dismissNoti", true);
            result = PendingIntent.getService(context, 0, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.addAction(R.drawable.ic_sysbar_null,
                    context.getResources().getString(R.string.quick_settings_reminder_noti_dismiss), result);

            // Add button for reminding later
            serviceIntent.putExtra("time", true);
            result = PendingIntent.getService(context, 2, serviceIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            builder.addAction(R.drawable.ic_qs_alarm_on,
                    context.getResources().getString(R.string.quick_settings_reminder_noti_later), result);

            shared.edit().putBoolean("scheduled", false).commit();
            shared.edit().putInt("hours", -1).commit();
            shared.edit().putInt("minutes", -1).commit();
            shared.edit().putInt("day", -1).commit();

            manager.notify(NOTI_ID, builder.build());
        }
    }
    shared.edit().putBoolean("updated", false).commit();
}