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:com.github.sryze.wirebug.DebugStatusService.java

private void updateStatus() {
    Log.i(TAG, "Performing a status update...");

    boolean isEnabled = DebugManager.isTcpDebuggingEnabled();
    if (isEnabled != isCurrentlyEnabled) {
        Log.i(TAG, String.format("Status has changed to %s", isEnabled ? "enabled" : "disabled"));
        sendStatusChangedBroadcast(isEnabled);
    } else {//w  ww  .  ja  va 2 s .  c o m
        Log.i(TAG, "Status is unchanged");
    }

    if (keyguardManager.inKeyguardRestrictedInputMode() && preferences.getBoolean("disable_on_lock", false)) {
        Log.i(TAG, "Disabling debugging because disable_on_lock is true");
        DebugManager.setTcpDebuggingEnabled(false);
    }

    if (isEnabled) {
        boolean isConnectedToWifi = NetworkUtils.isConnectedToWifi(connectivityManager);
        Log.d(TAG, String.format("Connected to Wi-Fi: %s", isConnectedToWifi ? "yes" : "no"));

        Intent contentIntent = new Intent(this, MainActivity.class);
        contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        Intent stopIntent = new Intent(this, DebugStatusService.class);
        stopIntent.setAction(ACTION_STOP);

        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
        notificationBuilder.setSmallIcon(R.drawable.ic_notification)
                .setContentTitle(getString(R.string.notification_title))
                .setContentIntent(
                        PendingIntent.getActivity(this, 0, contentIntent, PendingIntent.FLAG_CANCEL_CURRENT))
                .addAction(R.drawable.ic_stop, getString(R.string.notification_action_stop),
                        PendingIntent.getService(this, 0, stopIntent, PendingIntent.FLAG_CANCEL_CURRENT));

        if (isConnectedToWifi) {
            notificationBuilder.setContentText(String.format(getString(R.string.notification_text),
                    NetworkUtils.getWifiIpAddressString(wifiManager),
                    NetworkUtils.getWifiNetworkName(wifiManager)));
        } else {
            notificationBuilder.setContentText(getString(R.string.notification_text_not_connected));
        }

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            notificationBuilder.setCategory(Notification.CATEGORY_STATUS)
                    .setVisibility(Notification.VISIBILITY_PUBLIC);
        }

        Notification notification = notificationBuilder.build();
        notification.flags |= Notification.FLAG_NO_CLEAR;
        notificationManager.notify(STATUS_NOTIFICATION_ID, notification);
    } else {
        Log.d(TAG, "Canceling the notification");
        notificationManager.cancel(STATUS_NOTIFICATION_ID);
    }

    if (isEnabled && preferences.getBoolean("stay_awake", false)) {
        if (wakeLock != null && !wakeLock.isHeld()) {
            Log.i(TAG, "Acquiring a wake lock because stay_awake is true");
            wakeLock.acquire();
        }
    } else {
        if (wakeLock != null && wakeLock.isHeld()) {
            Log.i(TAG, "Releasing the wake lock");
            wakeLock.release();
        }
    }

    isCurrentlyEnabled = isEnabled;
}

From source file:com.concentricsky.android.khanacademy.app.HomeActivity.java

private void setupRepeatingLibraryUpdateAlarm() {
    Log.d(LOG_TAG, "setupRepeatingLibraryUpdateAlarm");
    AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);

    Intent intent = new Intent(getApplicationContext(), KADataService.class);
    intent.setAction(ACTION_LIBRARY_UPDATE);
    PendingIntent existing = PendingIntent.getService(getApplicationContext(),
            REQUEST_CODE_RECURRING_LIBRARY_UPDATE, intent, PendingIntent.FLAG_NO_CREATE);
    boolean alreadyScheduled = existing != null;

    if (!alreadyScheduled) {
        // Initial delay.
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.SECOND, UPDATE_DELAY_FROM_FIRST_RUN);

        // Schedule the alarm.
        PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(),
                REQUEST_CODE_RECURRING_LIBRARY_UPDATE, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        Log.d(LOG_TAG, "(re)setting alarm");
        am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                pendingIntent);//from w  ww  . j  ava2 s . c  o  m
    }
}

From source file:com.sean.takeastand.alarmprocess.UnscheduledRepeatingAlarm.java

private PendingIntent createPausePendingIntent(Context context) {
    Intent intent = new Intent(context, EndPauseReceiver.class);
    return PendingIntent.getBroadcast(context, PAUSE_ALARM_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.terracom.mumbleclient.service.QRPushToTalkNotification.java

/**
 * Called to update/create the service's foreground QRPushToTalk notification.
 *//*from w ww.j  av  a  2 s  .c  o  m*/
private Notification createNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(mService);
    builder.setSmallIcon(R.drawable.ic_stat_notify);
    builder.setTicker(mCustomTicker);
    builder.setContentTitle(mService.getString(R.string.app_name));
    builder.setContentText(mCustomContentText);
    builder.setPriority(NotificationCompat.PRIORITY_HIGH);
    builder.setOngoing(true);

    if (!mReconnecting) {
        // Add notification triggers
        Intent muteIntent = new Intent(BROADCAST_MUTE);
        Intent deafenIntent = new Intent(BROADCAST_DEAFEN);
        Intent overlayIntent = new Intent(BROADCAST_OVERLAY);

        builder.addAction(R.drawable.ic_action_microphone, mService.getString(R.string.mute),
                PendingIntent.getBroadcast(mService, 1, muteIntent, PendingIntent.FLAG_CANCEL_CURRENT));
        builder.addAction(R.drawable.ic_action_audio, mService.getString(R.string.deafen),
                PendingIntent.getBroadcast(mService, 1, deafenIntent, PendingIntent.FLAG_CANCEL_CURRENT));
        builder.addAction(R.drawable.ic_action_channels, mService.getString(R.string.overlay),
                PendingIntent.getBroadcast(mService, 2, overlayIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    } else {
        Intent cancelIntent = new Intent(BROADCAST_CANCEL_RECONNECT);
        builder.addAction(R.drawable.ic_action_delete_dark, mService.getString(R.string.cancel_reconnect),
                PendingIntent.getBroadcast(mService, 2, cancelIntent, PendingIntent.FLAG_CANCEL_CURRENT));
    }

    // Show unread messages
    if (mMessages.size() > 0) {
        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        for (String message : mMessages) {
            inboxStyle.addLine(message);
        }
        builder.setStyle(inboxStyle);
    }

    Intent channelListIntent = new Intent(mService, QRPushToTalkActivity.class);
    channelListIntent.putExtra(QRPushToTalkActivity.EXTRA_DRAWER_FRAGMENT, DrawerAdapter.ITEM_SERVER);
    // FLAG_CANCEL_CURRENT ensures that the extra always gets sent.
    PendingIntent pendingIntent = PendingIntent.getActivity(mService, 0, channelListIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    builder.setContentIntent(pendingIntent);

    Notification notification = builder.build();
    mService.startForeground(NOTIFICATION_ID, notification);
    return notification;
}

From source file:edu.mines.letschat.GcmIntentService.java

protected PendingIntent getDeleteIntent() {
    Intent resultBroadCastIntent = new Intent();
    resultBroadCastIntent.setAction("deletion");
    resultBroadCastIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    resultBroadCastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    sendBroadcast(resultBroadCastIntent);
    return PendingIntent.getBroadcast(getBaseContext(), 0, resultBroadCastIntent,
            PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:org.roman.findme.MainActivity.java

void startLocationService() {
    //        Intent intent = new Intent(this, AndroidLocationServices.class);
    //        startService(intent);

    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1253, intent,
            PendingIntent.FLAG_CANCEL_CURRENT);
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());
    AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    alarm.cancel(pendingIntent);/*from w  w  w . j a  v a2s .  c  om*/
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_HOUR,
            pendingIntent);

}

From source file:org.chromium.tools.audio_focus_grabber.AudioFocusGrabberListenerService.java

private PendingIntent createPendingIntent(String action) {
    Intent i = new Intent(this, AudioFocusGrabberListenerService.class);
    i.setAction(action);// ww w  . j  av a2 s  .  co m
    return PendingIntent.getService(this, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
}

From source file:com.nifcloud.mbaas.ncmbfcmplugin.NCMBFirebaseMessagingService.java

public NotificationCompat.Builder notificationSettings(Bundle pushData) {
    //AndroidManifest??
    ApplicationInfo appInfo = null;/*from www  .j  ava2s.  c  o  m*/
    Class startClass = null;
    String applicationName = null;
    String activityName = null;
    String packageName = null;
    int channelIcon = 0;
    try {
        appInfo = getPackageManager().getApplicationInfo(getPackageName(), PackageManager.GET_META_DATA);
        applicationName = getPackageManager()
                .getApplicationLabel(getPackageManager().getApplicationInfo(getPackageName(), 0)).toString();
        activityName = appInfo.packageName + ".UnityPlayerNativeActivity";
        packageName = appInfo.packageName;
    } catch (PackageManager.NameNotFoundException e) {
        throw new IllegalArgumentException(e);
    }

    Log.d("Unity", "activityName: " + activityName + "|  packageName:" + packageName);

    //Note FCM
    //????????
    Intent intent = new Intent(this, com.nifcloud.mbaas.ncmbfcmplugin.UnityPlayerActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.putExtras(pushData);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, new Random().nextInt(), intent,
            PendingIntent.FLAG_CANCEL_CURRENT);

    //pushData??
    String message = "";
    String title = "";
    if (pushData.getString("title") != null) {
        title = pushData.getString("title");
    } else {
        //title????????
        title = applicationName;
    }
    if (pushData.getString("message") != null) {
        message = pushData.getString("message");
    }

    //SmallIconmanifests???????
    int userSmallIcon = appInfo.metaData.getInt(SMALL_ICON_KEY);
    int icon;
    if (userSmallIcon != 0) {
        //manifests??????
        icon = userSmallIcon;
    } else {
        //?????
        icon = appInfo.icon;
    }
    //SmallIcon
    int smallIconColor = appInfo.metaData.getInt(SMALL_ICON_COLOR_KEY);

    //Notification?
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,
            com.nifcloud.mbaas.ncmbfcmplugin.NCMBNotificationUtils.getDefaultChannel()).setSmallIcon(icon)//?
                    .setColor(smallIconColor)//?
                    .setContentTitle(title).setContentText(message).setAutoCancel(true)//????
                    .setSound(defaultSoundUri)//?
                    .setContentIntent(pendingIntent);//????Activity
    return notificationBuilder;
}

From source file:net.olejon.spotcommander.WebViewActivity.java

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

    // Google API client
    mGoogleApiClient = new GoogleApiClient.Builder(mContext).addApiIfAvailable(Wearable.API).build();

    // Allow landscape?
    if (!mTools.allowLandscape())
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

    // Hide status bar?
    if (mTools.getDefaultSharedPreferencesBoolean("HIDE_STATUS_BAR"))
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

    // Power manager
    final PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);

    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "wakeLock");

    // Settings/*from  w  w  w.j  a  va  2 s  .com*/
    mTools.setSharedPreferencesBoolean("CAN_CLOSE_COVER", false);

    // Current network
    mCurrentNetwork = mTools.getCurrentNetwork();

    // Computer
    final long computerId = mTools.getSharedPreferencesLong("LAST_COMPUTER_ID");

    final String[] computer = mTools.getComputer(computerId);

    final String uri = computer[0];
    final String username = computer[1];
    final String password = computer[2];

    // Layout
    setContentView(R.layout.activity_webview);

    // Status bar color
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        mStatusBarPrimaryColor = getWindow().getStatusBarColor();
        mStatusBarCoverArtColor = mStatusBarPrimaryColor;
    }

    // Notification
    mPersistentNotificationIsSupported = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN);

    if (mPersistentNotificationIsSupported) {
        final Intent launchActivityIntent = new Intent(mContext, MainActivity.class);
        launchActivityIntent.setAction("android.intent.action.MAIN");
        launchActivityIntent.addCategory("android.intent.category.LAUNCHER");
        mLaunchActivityPendingIntent = PendingIntent.getActivity(mContext, 0, launchActivityIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent hideIntent = new Intent(mContext, RemoteControlIntentService.class);
        hideIntent.setAction("hide_notification");
        hideIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mHidePendingIntent = PendingIntent.getService(mContext, 0, hideIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent previousIntent = new Intent(mContext, RemoteControlIntentService.class);
        previousIntent.setAction("previous");
        previousIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPreviousPendingIntent = PendingIntent.getService(mContext, 0, previousIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent playPauseIntent = new Intent(mContext, RemoteControlIntentService.class);
        playPauseIntent.setAction("play_pause");
        playPauseIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mPlayPausePendingIntent = PendingIntent.getService(mContext, 0, playPauseIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent nextIntent = new Intent(mContext, RemoteControlIntentService.class);
        nextIntent.setAction("next");
        nextIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mNextPendingIntent = PendingIntent.getService(mContext, 0, nextIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeDownIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeDownIntent.setAction("adjust_spotify_volume_down");
        volumeDownIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeDownPendingIntent = PendingIntent.getService(mContext, 0, volumeDownIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        final Intent volumeUpIntent = new Intent(mContext, RemoteControlIntentService.class);
        volumeUpIntent.setAction("adjust_spotify_volume_up");
        volumeUpIntent.putExtra(RemoteControlIntentService.REMOTE_CONTROL_INTENT_SERVICE_EXTRA, computerId);
        mVolumeUpPendingIntent = PendingIntent.getService(mContext, 0, volumeUpIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        mNotificationManager = NotificationManagerCompat.from(mContext);
        mNotificationBuilder = new NotificationCompat.Builder(mContext);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
            mNotificationBuilder.setPriority(Notification.PRIORITY_MAX);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mNotificationBuilder.setVisibility(Notification.VISIBILITY_PUBLIC);
            mNotificationBuilder.setCategory(Notification.CATEGORY_TRANSPORT);
        }
    }

    // Web view
    mWebView = (WebView) findViewById(R.id.webview_webview);

    mWebView.setBackgroundColor(ContextCompat.getColor(mContext, R.color.background));
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_INSIDE_OVERLAY);

    mWebView.setWebViewClient(new WebViewClient() {
        @SuppressWarnings("deprecation")
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && !url.contains(uri)
                    && !url.contains("olejon.net/code/spotcommander/api/1/spotify/")
                    && !url.contains("accounts.spotify.com/") && !url.contains("facebook.com/")) {
                view.getContext().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));

                return true;
            }

            return false;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, @NonNull HttpAuthHandler handler, String host,
                String realm) {
            if (handler.useHttpAuthUsernamePassword()) {
                handler.proceed(username, password);
            } else {
                handler.cancel();

                mWebView.stopLoading();

                mTools.showToast(getString(R.string.webview_authentication_failed), 1);

                mTools.navigateUp(mActivity);
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest webResourceRequest,
                WebResourceError webResourceError) {
            mWebView.stopLoading();

            mTools.showToast(getString(R.string.webview_error), 1);

            mTools.navigateUp(mActivity);
        }

        @Override
        public void onReceivedSslError(WebView view, @NonNull SslErrorHandler handler, SslError error) {
            handler.cancel();

            mWebView.stopLoading();

            new MaterialDialog.Builder(mContext).title(R.string.webview_dialog_ssl_error_title)
                    .content(getString(R.string.webview_dialog_ssl_error_message))
                    .positiveText(R.string.webview_dialog_ssl_error_positive_button)
                    .onPositive(new MaterialDialog.SingleButtonCallback() {
                        @Override
                        public void onClick(@NonNull MaterialDialog materialDialog,
                                @NonNull DialogAction dialogAction) {
                            finish();
                        }
                    }).contentColorRes(R.color.black).show();
        }
    });

    // User agent
    mProjectVersionName = mTools.getProjectVersionName();

    final String uaAppend1 = (!username.equals("") && !password.equals("")) ? "AUTHENTICATION_ENABLED " : "";
    final String uaAppend2 = (mTools.getSharedPreferencesBoolean("WEAR_CONNECTED")) ? "WEAR_CONNECTED " : "";
    final String uaAppend3 = (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT
            && !mTools.getDefaultSharedPreferencesBoolean("HARDWARE_ACCELERATED_ANIMATIONS"))
                    ? "DISABLE_CSSTRANSITIONS DISABLE_CSSTRANSFORMS3D "
                    : "";

    // Web settings
    final WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setSupportZoom(false);
    webSettings.setUserAgentString(getString(R.string.webview_user_agent, webSettings.getUserAgentString(),
            mProjectVersionName, uaAppend1, uaAppend2, uaAppend3));

    // Load app
    if (savedInstanceState != null) {
        mWebView.restoreState(savedInstanceState);
    } else {
        mWebView.loadUrl(uri);
    }

    // JavaScript interface
    mWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
}

From source file:org.runbuddy.tomahawk.utils.MediaNotification.java

public MediaNotification(PlaybackService service) throws RemoteException {
    mService = service;//from w  w  w  . j  av a 2  s. c o m
    updateSessionToken();

    mNotificationColor = mService.getResources().getColor(R.color.notification_bg);

    mNotificationManager = NotificationManagerCompat.from(mService);
    stopNotification();

    String pkg = mService.getPackageName();
    mIntents.put(R.drawable.ic_action_favorites_small, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_FAVORITE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_action_favorites_small_underlined, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_UNFAVORITE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_av_pause, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PAUSE).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_av_play_arrow, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PLAY).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_player_previous_light, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_PREV).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
    mIntents.put(R.drawable.ic_player_next_light, PendingIntent.getBroadcast(mService, 100,
            new Intent(ACTION_NEXT).setPackage(pkg), PendingIntent.FLAG_CANCEL_CURRENT));
}