Example usage for android.app PendingIntent FLAG_CANCEL_CURRENT

List of usage examples for android.app PendingIntent FLAG_CANCEL_CURRENT

Introduction

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

Prototype

int FLAG_CANCEL_CURRENT

To view the source code for android.app PendingIntent FLAG_CANCEL_CURRENT.

Click Source Link

Document

Flag indicating that if the described PendingIntent already exists, the current one should be canceled before generating a new one.

Usage

From source file:me.tassoevan.cordova.ForegroundService.java

@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
private Notification makeNotification() {
    JSONObject settings = BackgroundPlugin.settings;
    Context context = getApplicationContext();
    String pkgName = context.getPackageName();
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(pkgName);

    Notification.Builder notification = new Notification.Builder(context)
            .setContentTitle(settings.optString("title", "")).setContentText(settings.optString("text", ""))
            .setTicker(settings.optString("ticker", "")).setOngoing(true).setSmallIcon(getIconResId());

    if (intent != null && settings.optBoolean("resume")) {
        PendingIntent contentIntent = PendingIntent.getActivity(context, NOTIFICATION_ID, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        notification.setContentIntent(contentIntent);
    }//from w  w  w.  ja v  a2s . com

    if (Build.VERSION.SDK_INT < 16) {
        return notification.getNotification();
    } else {
        return notification.build();
    }
}

From source file:im.vector.activity.CommonActivityUtils.java

/**
 * Restart the application after 100ms//from w  w  w .  j av  a2  s .co  m
 * @param activity activity
 */
public static void restartApp(Context activity) {
    PendingIntent mPendingIntent = PendingIntent.getActivity(activity, 314159,
            new Intent(activity, LoginActivity.class), PendingIntent.FLAG_CANCEL_CURRENT);

    // so restart the application after 100ms
    AlarmManager mgr = (AlarmManager) activity.getSystemService(activity.ALARM_SERVICE);
    mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);
    System.exit(0);
}

From source file:com.javathlon.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received.// w ww  .  ja  v  a  2s  . c  om
 */
private void sendNotification(String title, String message, String type, String url) {
    Intent resultIntent = null;

    if (type.equals("podcast")) {
        resultIntent = new Intent(this, MainActivity.class);
        resultIntent.putExtra("needdownloaded", "y");
        resultIntent.putExtra("rss", url);
        resultIntent.putExtra("action", "rsslist");

    } else if (type.equals("web")) {
        resultIntent = new Intent(this, WebViewActivity.class);
        resultIntent.putExtra("url", url);

    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 1 /* Request code */, resultIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.controllers_play).setContentTitle(title).setContentText(message)
            .setAutoCancel(true).setSound(defaultSoundUri)

            .setContentIntent(pendingIntent);

    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

}

From source file:com.tingtingapps.securesms.jobs.GcmRefreshJob.java

private void notifyGcmFailure() {
    Intent intent = new Intent(context, PlayServicesProblemActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 1122, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    builder.setSmallIcon(com.tingtingapps.securesms.R.drawable.icon_notification);
    builder.setLargeIcon(BitmapFactory.decodeResource(context.getResources(),
            com.tingtingapps.securesms.R.drawable.ic_action_warning_red));
    builder.setContentTitle(context.getString(
            com.tingtingapps.securesms.R.string.GcmRefreshJob_Permanent_TextSecure_communication_failure));
    builder.setContentText(context.getString(
            com.tingtingapps.securesms.R.string.GcmRefreshJob_TextSecure_was_unable_to_register_with_Google_Play_Services));
    builder.setTicker(context.getString(
            com.tingtingapps.securesms.R.string.GcmRefreshJob_Permanent_TextSecure_communication_failure));
    builder.setVibrate(new long[] { 0, 1000 });
    builder.setContentIntent(pendingIntent);

    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(12, builder.build());
}

From source file:it.unicaradio.android.services.GCMIntentService.java

private Notification createNotification(Intent i) {
    String text = i.getStringExtra("message");
    String intentPriority = i.getStringExtra("priority");
    GcmMessagePriority priorityEnum = GcmMessagePriority.fromString(intentPriority);
    int priority = priorityEnum.toAndroidNotificationPriority();

    Log.v("GCM", "NOTIFYING A MESSAGE: \"" + text + "\" with priority: " + intentPriority);

    Intent intent = new Intent(ACTION_GCM_MESSAGE);
    intent.putExtra("text", text);

    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    Builder b = new NotificationCompat.Builder(this);
    b.setContentTitle("Nuovo messaggio!");
    b.setContentText(text);// w  ww .ja  v a  2  s .com
    b.setSmallIcon(R.drawable.ic_stat_notify);
    b.setContentIntent(pIntent);
    b.setWhen(System.currentTimeMillis());
    b.setPriority(priority);
    b.setAutoCancel(true);
    b.setVibrate(new long[] { 100L, 600L });

    return b.build();
}

From source file:com.allthatseries.RNAudioPlayer.MediaNotificationManager.java

public MediaNotificationManager(AudioPlayerService service) throws RemoteException {
    mService = service;/*w  w w. j av  a 2 s  . c  o  m*/
    updateSessionToken();

    mNotificationManager = NotificationManagerCompat.from(service);

    String pkg = mService.getPackageName();
    mPauseIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PAUSE).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPlayIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_PLAY).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);
    mPreviousIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT);
    mNextIntent = PendingIntent.getBroadcast(mService, REQUEST_CODE, new Intent(ACTION_NEXT).setPackage(pkg),
            PendingIntent.FLAG_CANCEL_CURRENT);

    // Cancel all notifications to handle the case where the Service was killed and
    // restarted by the system.
    mNotificationManager.cancelAll();
}

From source file:org.thoughtcrime.securesms.jobs.GcmRefreshJob.java

private void notifyGcmFailure() {
    Intent intent = new Intent(context, PlayServicesProblemActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 1122, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    builder.setSmallIcon(R.drawable.icon_notification);
    builder.setLargeIcon(//from ww  w . j  a  va  2 s.  com
            BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_action_warning_red));
    builder.setContentTitle(
            context.getString(R.string.GcmRefreshJob_Permanent_TextSecure_communication_failure));
    builder.setContentText(context
            .getString(R.string.GcmRefreshJob_TextSecure_was_unable_to_register_with_Google_Play_Services));
    builder.setTicker(context.getString(R.string.GcmRefreshJob_Permanent_TextSecure_communication_failure));
    builder.setVibrate(new long[] { 0, 1000 });
    builder.setContentIntent(pendingIntent);

    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(12, builder.build());
}

From source file:com.csipsimple.plugins.twvoip.CallHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) {

        PendingIntent pendingIntent = null;
        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // We must handle that clean way cause when call just to
        // get the row in account list expect this to reply correctly
        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr)
                && !TextUtils.isEmpty(pwd)) {
            // Build pending intent
            Intent i = new Intent(ACTION_DO_TWVOIP_CALL);
            i.setClass(context, getClass());
            i.putExtra(Intent.EXTRA_PHONE_NUMBER, number);

            pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
            // = PendingIntent.getActivity(context, 0, i, 0);
        }//  w ww.  jav  a  2 s .  c  om

        // Build icon
        Bitmap bmp = null;
        Drawable icon = context.getResources().getDrawable(R.drawable.icon);
        BitmapDrawable bd = ((BitmapDrawable) icon);
        bmp = bd.getBitmap();

        // Build the result for the row (label, icon, pending intent, and
        // excluded phone number)
        Bundle results = getResultExtras(true);
        if (pendingIntent != null) {
            results.putParcelable(Intent.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }
        results.putString(Intent.EXTRA_TITLE, "12voip WebCallback");
        if (bmp != null) {
            results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp);
        }

        // DO *NOT* exclude from next tel: intent cause we use a http method
        // results.putString(Intent.EXTRA_PHONE_NUMBER, number);

    } else if (ACTION_DO_TWVOIP_CALL.equals(intent.getAction())) {

        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // params
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("username", user));
        params.add(new BasicNameValuePair("password", pwd));
        params.add(new BasicNameValuePair("from", nbr));
        params.add(new BasicNameValuePair("to", number));
        String paramString = URLEncodedUtils.format(params, "utf-8");

        String requestURL = "https://www.12voip.com//myaccount/makecall.php?" + paramString;

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(requestURL);

        // Create a response handler
        HttpResponse httpResponse;
        try {
            httpResponse = httpClient.execute(httpGet);
            Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent());
                BufferedReader br = new BufferedReader(isr);

                String line;
                String fullReply = "";
                boolean foundSuccess = false;
                while ((line = br.readLine()) != null) {
                    if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) {
                        showToaster(context, "Success... wait a while you'll called back");
                        foundSuccess = true;
                        break;
                    }
                    if (!TextUtils.isEmpty(line)) {
                        fullReply = fullReply.concat(line);
                    }
                }
                if (!foundSuccess) {
                    showToaster(context, "Error : server error : " + fullReply);
                }
            } else {
                showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        } catch (IOException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        }

    }
}

From source file:com.nks.nksmod.otaupdater.DownloadReceiver.java

@Override
public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action == null)
        return;/* www .j  av  a 2s.  c om*/

    if (action.equals(DL_ROM_ACTION)) {
        RomInfo.FACTORY.clearUpdateNotif(context);
        RomInfo.FACTORY.fromIntent(intent).startDownload(context);
        /* } else if (action.equals(DL_KERNEL_ACTION)) {
            KernelInfo.FACTORY.clearUpdateNotif(context);
            KernelInfo.FACTORY.fromIntent(intent).startDownload(context); */
    } else if (action.equals(CLEAR_DL_ACTION)) {
        if (intent.hasExtra(DownloadManager.EXTRA_DOWNLOAD_ID)) {
            DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
            dm.remove(intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1));
            DownloadBarFragment.notifyActiveFragment();
        }
    } else if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
        DownloadStatus status = DownloadStatus.forDownloadID(context,
                intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1));
        if (status == null)
            return;

        BaseInfo info = status.getInfo();
        if (info == null)
            return;

        int error = status.getStatus() == DownloadManager.STATUS_SUCCESSFUL ? info.checkDownloadedFile()
                : status.getReason();

        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

        if (error == 0) {
            Intent mainIntent = new Intent(context, OTAUpdaterActivity.class);
            mainIntent.setAction(info.getNotifAction());
            mainIntent.putExtra(OTAUpdaterActivity.EXTRA_FLAG_DOWNLOAD_DIALOG, true);
            PendingIntent mainPIntent = PendingIntent.getActivity(context, 0, mainIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Intent flashIntent = new Intent(context, DownloadsActivity.class);
            flashIntent.setAction(info.getFlashAction());
            info.addToIntent(flashIntent);
            PendingIntent flashPIntent = PendingIntent.getActivity(context, 0, flashIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Notification notif = new NotificationCompat.Builder(context)
                    .setTicker(context.getString(info.getDownloadDoneTitle()))
                    .setContentTitle(context.getString(info.getDownloadDoneTitle()))
                    .setSmallIcon(R.drawable.ic_stat_av_download)
                    .setContentText(context.getString(R.string.notif_completed)).setContentIntent(mainPIntent)
                    .addAction(R.drawable.ic_action_system_update, context.getString(R.string.install),
                            flashPIntent)
                    .build();
            nm.notify(info.getFlashNotifID(), notif);
        } else {
            Intent mainIntent = new Intent(context, OTAUpdaterActivity.class);
            mainIntent.setAction(info.getNotifAction());
            info.addToIntent(mainIntent);
            PendingIntent mainPIntent = PendingIntent.getActivity(context, 0, mainIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Intent dlIntent = new Intent(context, DownloadReceiver.class);
            dlIntent.setAction(info.getDownloadAction());
            info.addToIntent(dlIntent);
            PendingIntent dlPIntent = PendingIntent.getBroadcast(context, 1, dlIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Intent clearIntent = new Intent(context, DownloadReceiver.class);
            clearIntent.setAction(CLEAR_DL_ACTION);
            clearIntent.putExtra(DownloadManager.EXTRA_DOWNLOAD_ID, status.getId());
            PendingIntent clearPIntent = PendingIntent.getBroadcast(context, 2, clearIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);

            Notification notif = new NotificationCompat.Builder(context)
                    .setTicker(context.getString(info.getDownloadFailedTitle()))
                    .setContentTitle(context.getString(info.getDownloadFailedTitle()))
                    .setContentText(status.getErrorString(context)).setSmallIcon(R.drawable.ic_stat_warning)
                    .setContentIntent(mainPIntent).setDeleteIntent(clearPIntent)
                    .addAction(R.drawable.ic_action_refresh, context.getString(R.string.retry), dlPIntent)
                    .build();
            nm.notify(info.getFailedNotifID(), notif);
        }
    } else if (action.equals(DownloadManager.ACTION_NOTIFICATION_CLICKED)) {
        long[] ids = intent.getLongArrayExtra(DownloadManager.EXTRA_NOTIFICATION_CLICK_DOWNLOAD_IDS);
        if (ids.length == 0)
            return;

        DownloadStatus status = DownloadStatus.forDownloadID(context, ids[0]);
        if (status == null)
            return;

        BaseInfo info = status.getInfo();
        if (info == null)
            return;

        Intent i = new Intent(context, OTAUpdaterActivity.class);
        i.setAction(info.getNotifAction());
        i.putExtra(OTAUpdaterActivity.EXTRA_FLAG_DOWNLOAD_DIALOG, true);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

From source file:net.xisberto.work_schedule.alarm.CountdownService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null) {
        if (ACTION_START.equals(intent.getAction())) {
            if (intent.hasExtra(AlarmMessageActivity.EXTRA_PERIOD_ID)) {
                int period_id = intent.getIntExtra(AlarmMessageActivity.EXTRA_PERIOD_ID,
                        R.string.fstp_entrance);
                period = Period.getPeriod(this, period_id);
            } else {
                stopSelf();/*ww  w  . j a  v  a  2s . c  o  m*/
                return super.onStartCommand(intent, flags, startId);
            }

            long millisInFuture = period.time.getTimeInMillis() - System.currentTimeMillis();
            if (millisInFuture > 0) {

                Intent mainIntent = new Intent(this, MainActivity.class);
                mainIntent.setAction(MainActivity.ACTION_SET_PERIOD);
                mainIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                Intent deleteIntent = new Intent(this, CountdownService.class);
                deleteIntent.setAction(ACTION_STOP);

                builder = new Builder(this).setSmallIcon(R.drawable.ic_stat_notification)
                        .setContentTitle(getString(period.getLabelId()))
                        .setTicker(getString(period.getLabelId())).setOnlyAlertOnce(true)
                        .setPriority(NotificationCompat.PRIORITY_LOW).setAutoCancel(false)
                        .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                        .setContentIntent(PendingIntent.getActivity(this, period.getId(), mainIntent,
                                PendingIntent.FLAG_CANCEL_CURRENT))
                        .setDeleteIntent(PendingIntent.getService(this, period.getId(), deleteIntent,
                                PendingIntent.FLAG_CANCEL_CURRENT));
                manager = ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE));
                manager.notify(0, builder.build());

                timer = new CountDownTimer(millisInFuture, 1000) {

                    @Override
                    public void onTick(long millisUntilFinished) {
                        Time t = new Time();
                        t.set(millisUntilFinished);
                        builder.setContentText(getString(R.string.time_until_alarm, t.format("%M:%S")));
                        manager.notify(0, builder.build());
                    }

                    @Override
                    public void onFinish() {
                        manager.cancel(0);
                        stopSelf();
                    }
                };

                timer.start();
            }
        } else if (ACTION_STOP_SPECIFIC.equals(intent.getAction())) {
            if (intent.hasExtra(AlarmMessageActivity.EXTRA_PERIOD_ID)) {
                int period_id = intent.getIntExtra(AlarmMessageActivity.EXTRA_PERIOD_ID,
                        R.string.fstp_entrance);
                if (period != null && period.getId() == period_id) {
                    stopAndCancel();
                }
            } else {
                stopSelf();
                return super.onStartCommand(intent, flags, startId);
            }
        } else if (ACTION_STOP.equals(intent.getAction())) {
            stopAndCancel();
        }

    }
    return super.onStartCommand(intent, flags, startId);
}