Example usage for android.content Intent FLAG_ACTIVITY_CLEAR_TOP

List of usage examples for android.content Intent FLAG_ACTIVITY_CLEAR_TOP

Introduction

In this page you can find the example usage for android.content Intent FLAG_ACTIVITY_CLEAR_TOP.

Prototype

int FLAG_ACTIVITY_CLEAR_TOP

To view the source code for android.content Intent FLAG_ACTIVITY_CLEAR_TOP.

Click Source Link

Document

If set, and the activity being launched is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it will be closed and this Intent will be delivered to the (now on top) old activity as a new Intent.

Usage

From source file:com.facebook.notifications.NotificationsManager.java

/**
 * Present a {@link Notification} to be presented from a GCM push bundle.
 * <p/>//from   w w  w.  java  2  s  .co  m
 * This does not present a notification immediately, instead it caches the assets from the
 * notification bundle, and then presents a notification to the user. This allows for a smoother
 * interaction without loading indicators for the user.
 * <p/>
 * Note that only one notification can be created for a specific push bundle, should you attempt
 * to present a new notification with the same payload bundle as an existing notification, it will
 * replace and update the old notification.
 *
 * @param context              The context to send the notification from
 * @param notificationBundle   The content of the push notification
 * @param launcherIntent       The launcher intent that contains your Application's activity.
 *                             This will be modified with the FLAG_ACTIVITY_CLEAR_TOP and
 *                             FLAG_ACTIVITY_SINGLE_TOP flags, in order to properly show the
 *                             notification in an already running application.
 *                             <p/>
 *                             Should you not want this behavior, you may use the notificationExtender
 *                             parameter to customize the contentIntent of the notification before
 *                             presenting it.
 * @param notificationExtender A nullable argument that allows you to customize the notification
 *                             before displaying it. Use this to configure Icons, text, sounds,
 *                             etc. before we pass the notification off to the OS.
 */
public static boolean presentNotification(@NonNull final Context context,
        @NonNull final Bundle notificationBundle, @NonNull final Intent launcherIntent,
        @Nullable final NotificationExtender notificationExtender) {
    final JSONObject alert;
    final int payloadHash;

    try {
        String payload = notificationBundle.getString(CARD_PAYLOAD_KEY);
        if (payload == null) {
            return false;
        }
        payloadHash = payload.hashCode();

        JSONObject payloadObject = new JSONObject(payload);
        alert = payloadObject.optJSONObject("alert") != null ? payloadObject.optJSONObject("alert")
                : new JSONObject();
    } catch (JSONException ex) {
        Log.e(LOG_TAG, "Error while parsing notification bundle JSON", ex);
        return false;
    }

    final boolean[] success = new boolean[1];

    final Thread backgroundThread = new Thread(new Runnable() {
        @Override
        public void run() {
            Looper.prepare();
            prepareCard(context, notificationBundle, new PrepareCallback() {
                @Override
                public void onPrepared(@NonNull Intent presentationIntent) {
                    Intent contentIntent = new Intent(launcherIntent);
                    contentIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    contentIntent.putExtra(EXTRA_PAYLOAD_INTENT, presentationIntent);

                    NotificationManager manager = (NotificationManager) context
                            .getSystemService(Context.NOTIFICATION_SERVICE);
                    Notification.Builder builder = new Notification.Builder(context)
                            .setSmallIcon(android.R.drawable.ic_dialog_alert)
                            .setContentTitle(alert.optString("title")).setContentText(alert.optString("body"))
                            .setAutoCancel(true)
                            .setContentIntent(PendingIntent.getActivity(context.getApplicationContext(),
                                    payloadHash, contentIntent, PendingIntent.FLAG_ONE_SHOT));

                    if (notificationExtender != null) {
                        builder = notificationExtender.extendNotification(builder);
                    }

                    manager.notify(NOTIFICATION_TAG, payloadHash, builder.getNotification());
                    success[0] = true;
                    Looper.myLooper().quit();
                }

                @Override
                public void onError(@NonNull Exception exception) {
                    Log.e(LOG_TAG, "Error while preparing card", exception);
                    Looper.myLooper().quit();
                }
            });

            Looper.loop();
        }
    });

    backgroundThread.start();

    try {
        backgroundThread.join();
    } catch (InterruptedException ex) {
        Log.e(LOG_TAG, "Failed to wait for background thread", ex);
        return false;
    }
    return success[0];
}

From source file:com.audiokernel.euphonyrmt.SearchActivity.java

@Override
public boolean onOptionsItemSelected(final MenuItem item) {
    boolean handled = true;

    switch (item.getItemId()) {
    case R.id.menu_search:
        onSearchRequested();//from   ww w. j a v  a 2 s.  com
        break;
    case android.R.id.home:
        final Intent intent = new Intent(this, MainMenuActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
        break;
    default:
        handled = false;
        break;
    }

    return handled;
}

From source file:com.ayuget.redface.ui.activity.BaseDrawerActivity.java

private void onNavDrawerItemClicked(DrawerItem drawerItem) {
    if (drawerItem.isSimpleItem()) {
        SimpleDrawerItem simpleDrawerItem = (SimpleDrawerItem) drawerItem;

        switch (simpleDrawerItem.getItemId()) {
        case NAVDRAWER_ITEM_MY_TOPICS:
            if (this instanceof TopicsActivity) {
                onMyTopicsClicked();//  ww w .j  a  v  a 2s. c o  m
            } else {
                Intent intent = new Intent(this, TopicsActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.putExtra(UIConstants.ARG_SELECTED_CATEGORY, categoriesStore.getMetaCategory());
                startActivity(intent);
            }

            drawerLayout.closeDrawers();
            break;
        case NAVDRAWER_ITEM_PRIVATE_MESSAGES: {
            Intent intent = new Intent(this, PrivateMessagesActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;
        }
        case NAVDRAWER_ITEM_PROFILE: {
            Intent intent = new Intent(this, AccountActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(UIConstants.ARG_RELOGIN_MODE, true);
            startActivity(intent);
            break;
        }
        case NAVDRAWER_ITEM_SETTINGS: {
            Intent intent = new Intent(this, SettingsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            break;
        }
        }
    } else if (drawerItem.isCategory()) {
        CategoryDrawerItem categoryDrawerItem = (CategoryDrawerItem) drawerItem;

        if (this instanceof TopicsActivity) {
            onCategoryClicked(categoryDrawerItem.getCategory());
        } else {
            Intent intent = new Intent(this, TopicsActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.putExtra(UIConstants.ARG_SELECTED_CATEGORY, categoryDrawerItem.getCategory());
            startActivity(intent);
        }
    }

    drawerLayout.closeDrawers();
}

From source file:com.android.nobadgift.DashboardActivity.java

/**
 * Go back to the home activity./*from www.  j a v  a  2s. co  m*/
 * 
 * @param context Context
 * @return void
 */

public void goHome(Context context) {
    final Intent intent = new Intent(context, HomeActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    context.startActivity(intent);
}

From source file:com.google.appinventor.components.runtime.ProbeBase.java

@SimpleFunction(description = "Create a notication with message to wake up "
        + "another activity when tap on the notification")
public void CreateNotification(String title, String text, boolean enabledSound, boolean enabledVibrate,
        String packageName, String className, String extraKey, String extraVal) throws ClassNotFoundException {

    Intent activityToLaunch = new Intent(Intent.ACTION_MAIN);

    Log.i(TAG, "packageName: " + packageName);
    Log.i(TAG, "className: " + className);

    // for local AI instance, all classes are under the package
    // "appinventor.ai_test"
    // but for those runs on Google AppSpot(AppEngine), the package name will be
    // "appinventor.ai_GoogleAccountUserName"
    // e.g. pakageName = appinventor.ai_HomerSimpson.HelloPurr
    // && className = appinventor.ai_HomerSimpson.HelloPurr.Screen1

    ComponentName component = new ComponentName(packageName, className);
    activityToLaunch.setComponent(component);
    activityToLaunch.putExtra(extraKey, extraVal);

    Log.i(TAG, "we found the class for intent to send into notificaiton");

    activityToLaunch.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    mContentIntent = PendingIntent.getActivity(mainUIThreadActivity, 0, activityToLaunch, 0);

    Long currentTimeMillis = System.currentTimeMillis();
    notification = new Notification(R.drawable.stat_notify_chat, "Activate Notification!", currentTimeMillis);

    Log.i(TAG, "After creating notification");
    notification.contentIntent = mContentIntent;
    notification.flags = Notification.FLAG_AUTO_CANCEL;

    // reset the notification
    notification.defaults = 0;//from   w  w w .ja v a  2 s .c  om

    if (enabledSound)
        notification.defaults |= Notification.DEFAULT_SOUND;

    if (enabledVibrate)
        notification.defaults |= Notification.DEFAULT_VIBRATE;

    notification.setLatestEventInfo(mainUIThreadActivity, (CharSequence) title, (CharSequence) text,
            mContentIntent);
    Log.i(TAG, "after updated notification contents");
    mNM.notify(PROBE_NOTIFICATION_ID, notification);
    Log.i(TAG, "notified");

}

From source file:com.example.pyrkesa.shwc.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {
        if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {//www .  ja  va  2 s . c  om
            mDrawerLayout.openDrawer(mDrawerList);
        }
    }
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.quit) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("Exit me", true);
        startActivity(intent);

    }

    if (id == R.id.log_out) {

        String android_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);

        new LogOut().execute(android_id);

    }
    return super.onOptionsItemSelected(item);
}

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

@Override
public void onClick(View view) {
    int id = view.getId();
    ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
    switch (id) {
    case R.id.chat_send:

        smiliesShell.setVisibility(View.GONE);
        EditText message = (EditText) findViewById(R.id.chat_text);
        String messageT = message.getText().toString();
        if (messageT.length() == 0) {
            Toast.makeText(this, R.string.no_message, Toast.LENGTH_SHORT).show();
            return;
        }/*from   w  w w  . j  a  v a  2s .  c om*/
        if (messageT.length() > 140) {
            Toast.makeText(this, R.string.message_too_long, Toast.LENGTH_SHORT).show();
            return;
        }
        nvp.add(new BasicNameValuePair("message", messageT));
        doSubmit("chatform", nvp, true);
        doChatScroll = true;
        break;
    case R.id.med_send:
        int w = walkingPicker.getValue();
        int s = sittingPicker.getValue();

        if (w == 0 && s == 0) {
            Toast.makeText(this, R.string.no_time, Toast.LENGTH_SHORT).show();
            return;
        }

        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt("walking", w);
        editor.putInt("sitting", s);
        editor.apply();

        lastWalking = w * 5;
        lastSitting = s * 5;

        startMeditating = true;

        nvp.add(new BasicNameValuePair("walking", lastWalking + ""));
        nvp.add(new BasicNameValuePair("sitting", lastSitting + ""));
        doSubmit("timeform", nvp, true);
        break;
    case R.id.med_cancel:

        Intent rIntent = new Intent(this, ReceiverAlarm.class);
        PendingIntent walkPendingIntent = PendingIntent.getBroadcast(context, 0, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent sitPendingIntent = PendingIntent.getBroadcast(context, 1, rIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        mAlarmMgr.cancel(walkPendingIntent);
        mAlarmMgr.cancel(sitPendingIntent);
        mNM.cancelAll();

        doSubmit("cancelform", nvp, true);
        break;
    case R.id.smily_button:
        if (smiliesShell.getVisibility() == View.GONE)
            smiliesShell.setVisibility(View.VISIBLE);
        else
            smiliesShell.setVisibility(View.GONE);
        break;
    case R.id.chat_text:
        smiliesShell.setVisibility(View.GONE);
        singleClick++;
        Handler handler = new Handler();
        Runnable r = new Runnable() {

            @Override
            public void run() {
                singleClick = 0;
            }
        };

        if (singleClick == 1) {
            //Single click
            handler.postDelayed(r, 250);
        } else if (singleClick == 2) {
            //Double click
            singleClick = 0;
            ((EditText) findViewById(R.id.chat_text)).setText("");
        }
        break;
    case R.id.new_commit:
        Intent i = new Intent(this, ActivityCommit.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        break;
    default:
        smiliesShell.setVisibility(View.GONE);
        break;
    }
}

From source file:de.lespace.apprtc.activity.ConnectActivity.java

private void connectToUser() {

    Intent newIntent = new Intent(this, CallActivity.class);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    newIntent.putExtra("keep", true);
    newIntent.putExtras(intent);/*from   w  w w  . j  a v a 2  s  .c o m*/
    startActivityForResult(newIntent, CONNECTION_REQUEST);

}

From source file:at.alladin.rmbt.android.test.RMBTLoopService.java

private void setFinishedNotification() {
    Intent notificationIntent = new Intent(getApplicationContext(), RMBTMainActivity.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent openAppIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);

    final Resources res = getResources();
    final Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.stat_icon_loop)
            .setContentTitle(res.getText(R.string.loop_notification_finished_title))
            .setTicker(res.getText(R.string.loop_notification_finished_ticker)).setContentIntent(openAppIntent)
            .build();//from   w w w. j a  va2  s.c om

    //notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(NotificationIDs.LOOP_ACTIVE, notification);
}

From source file:com.battlelancer.seriesguide.service.NotificationService.java

private void onNotify(final Cursor upcomingEpisodes, List<Integer> notifyPositions, long latestAirtime) {
    final Context context = getApplicationContext();

    CharSequence tickerText;// www . j a v  a 2  s .c  om
    CharSequence contentTitle;
    CharSequence contentText;
    PendingIntent contentIntent;
    // base intent for task stack
    final Intent showsIntent = new Intent(context, ShowsActivity.class);
    showsIntent.putExtra(ShowsActivity.InitBundle.SELECTED_TAB, ShowsActivity.InitBundle.INDEX_TAB_UPCOMING);

    final int count = notifyPositions.size();
    if (count == 1) {
        // notify in detail about one episode
        Timber.d("Notifying about 1 new episode");
        upcomingEpisodes.moveToPosition(notifyPositions.get(0));

        final String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
        tickerText = getString(R.string.upcoming_show, showTitle);
        contentTitle = showTitle + " "
                + Utils.getEpisodeNumber(this, upcomingEpisodes.getInt(NotificationQuery.SEASON),
                        upcomingEpisodes.getInt(NotificationQuery.NUMBER));

        // "8:00 PM on Network"
        final String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
        final String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
        contentText = getString(R.string.upcoming_show_detailed, releaseTime, network);

        Intent episodeDetailsIntent = new Intent(context, EpisodesActivity.class);
        episodeDetailsIntent.putExtra(EpisodesActivity.InitBundle.EPISODE_TVDBID,
                upcomingEpisodes.getInt(NotificationQuery._ID));
        episodeDetailsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);

        contentIntent = TaskStackBuilder.create(context).addNextIntent(showsIntent)
                .addNextIntent(episodeDetailsIntent)
                .getPendingIntent(REQUEST_CODE_SINGLE_EPISODE, PendingIntent.FLAG_CANCEL_CURRENT);
    } else {
        // notify about multiple episodes
        Timber.d("Notifying about " + count + " new episodes");
        tickerText = getString(R.string.upcoming_episodes);
        contentTitle = getString(R.string.upcoming_episodes_number, count);
        contentText = getString(R.string.upcoming_display);

        contentIntent = TaskStackBuilder.create(context)
                .addNextIntent(showsIntent.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime))
                .getPendingIntent(REQUEST_CODE_MULTIPLE_EPISODES, PendingIntent.FLAG_CANCEL_CURRENT);
    }

    final NotificationCompat.Builder nb = new NotificationCompat.Builder(context);

    if (AndroidUtils.isJellyBeanOrHigher()) {
        Timber.d("Building rich notification (JB+)");
        // JELLY BEAN and above
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));

            final String episodeTitle = upcomingEpisodes.getString(NotificationQuery.TITLE);
            final String episodeSummary = upcomingEpisodes.getString(NotificationQuery.OVERVIEW);

            final SpannableStringBuilder bigText = new SpannableStringBuilder();
            bigText.append(TextUtils.isEmpty(episodeTitle) ? "" : episodeTitle);
            bigText.setSpan(new StyleSpan(Typeface.BOLD), 0, bigText.length(), 0);
            bigText.append("\n");
            bigText.append(TextUtils.isEmpty(episodeSummary) ? "" : episodeSummary);

            nb.setStyle(new NotificationCompat.BigTextStyle().bigText(bigText).setSummaryText(contentText));

            // Action button to check in
            Intent checkInActionIntent = new Intent(context, QuickCheckInActivity.class);
            checkInActionIntent.putExtra(QuickCheckInActivity.InitBundle.EPISODE_TVDBID,
                    upcomingEpisodes.getInt(NotificationQuery._ID));
            checkInActionIntent
                    .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
            PendingIntent checkInIntent = PendingIntent.getActivity(context, REQUEST_CODE_ACTION_CHECKIN,
                    checkInActionIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            nb.addAction(R.drawable.ic_action_checkin, getString(R.string.checkin), checkInIntent);
        } else {
            // multiple episodes
            NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();

            // display at most the first five
            for (int displayIndex = 0; displayIndex < Math.min(count, 5); displayIndex++) {
                if (!upcomingEpisodes.moveToPosition(notifyPositions.get(displayIndex))) {
                    // could not go to the desired position (testing just in case)
                    break;
                }

                final SpannableStringBuilder lineText = new SpannableStringBuilder();

                // show title
                String showTitle = upcomingEpisodes.getString(NotificationQuery.SHOW_TITLE);
                lineText.append(TextUtils.isEmpty(showTitle) ? "" : showTitle);
                lineText.setSpan(new StyleSpan(Typeface.BOLD), 0, lineText.length(), 0);

                lineText.append(" ");

                // "8:00 PM on Network"
                String releaseTime = TimeTools.formatToLocalReleaseTime(this, TimeTools.getEpisodeReleaseTime(
                        this, upcomingEpisodes.getLong(NotificationQuery.EPISODE_FIRST_RELEASE_MS)));
                String network = upcomingEpisodes.getString(NotificationQuery.NETWORK);
                lineText.append(getString(R.string.upcoming_show_detailed, releaseTime, network));

                inboxStyle.addLine(lineText);
            }

            // tell if we could not display all episodes
            if (count > 5) {
                inboxStyle.setSummaryText(getString(R.string.more, count - 5));
            }

            nb.setStyle(inboxStyle);
            nb.setContentInfo(String.valueOf(count));
        }
    } else {
        // ICS and below
        if (count == 1) {
            // single episode
            upcomingEpisodes.moveToPosition(notifyPositions.get(0));
            maybeSetPoster(context, nb, upcomingEpisodes.getString(NotificationQuery.POSTER));
        }
    }

    // notification sound
    final String ringtoneUri = NotificationSettings.getNotificationsRingtone(context);
    // If the string is empty, the user chose silent...
    if (ringtoneUri.length() != 0) {
        // ...otherwise set the specified ringtone
        Timber.d("Notification has sound");
        nb.setSound(Uri.parse(ringtoneUri));
    }
    // vibration
    if (NotificationSettings.isNotificationVibrating(context)) {
        Timber.d("Notification vibrates");
        nb.setVibrate(VIBRATION_PATTERN);
    }
    nb.setDefaults(Notification.DEFAULT_LIGHTS);
    nb.setWhen(System.currentTimeMillis());
    nb.setAutoCancel(true);
    nb.setTicker(tickerText);
    nb.setContentTitle(contentTitle);
    nb.setContentText(contentText);
    nb.setContentIntent(contentIntent);
    nb.setSmallIcon(R.drawable.ic_notification);
    nb.setColor(getResources().getColor(R.color.accent_primary));
    nb.setPriority(NotificationCompat.PRIORITY_DEFAULT);
    nb.setCategory(NotificationCompat.CATEGORY_EVENT);

    Timber.d("Setting delete intent with episode time: " + latestAirtime);
    Intent i = new Intent(this, NotificationService.class);
    i.putExtra(KEY_EPISODE_CLEARED_TIME, latestAirtime);
    PendingIntent deleteIntent = PendingIntent.getService(this, REQUEST_CODE_DELETE_INTENT, i,
            PendingIntent.FLAG_CANCEL_CURRENT);
    nb.setDeleteIntent(deleteIntent);

    // build the notification
    Notification notification = nb.build();

    // use string resource id, always unique within app
    final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    nm.notify(R.string.upcoming_show, notification);
}