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.parse.CN1ParsePushBroadcastReceiver.java

@Override
protected void onPushOpen(Context context, Intent intent) {
    /*//  w ww.  j  a v a 2s  .c  o m
     Adapted from ParsePushBroadcastReceiver. Main changes:
     1. Adapted code for starting app activity since it caused problems (see 
    comments towards the end of the method starting from line 'Original code'
     2. Implemented necessary ParsePush callback to set push data in advance
    so that it will be available when the app activity is started/resumed
     */
    // Send a Parse Analytics "push opened" event
    ParseAnalytics.trackAppOpenedInBackground(intent);

    JSONObject pushData = null;
    String uriString = null;
    try {
        pushData = new JSONObject(intent.getStringExtra(ParsePushBroadcastReceiver.KEY_PUSH_DATA));
        uriString = pushData.optString("uri", null);
    } catch (JSONException e) {
        writeErrorLog("Unexpected JSONException when parsing " + "push data from opened notification: " + e);
    }

    writeDebugLog("Push opened: " + (pushData == null ? "<no payload>" : pushData.toString()));

    if (pushData != null) {
        // Forward payload so that it is available when app is opened via the push message
        ParsePush.handlePushOpen(pushData.toString(), CN1AndroidApplication.isAppInForeground());
        writeDebugLog("Notified ParsePush of opened push notification");
    }

    Class<? extends Activity> cls = getActivity(context, intent);

    Intent activityIntent;
    if (uriString != null) {
        writeDebugLog("Creating an intent to view URI: " + uriString);
        activityIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(uriString));
    } else {
        activityIntent = new Intent(context, cls);
    }

    activityIntent.putExtras(intent.getExtras());
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    activityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Original code
    //        /*
    //         In order to remove dependency on android-support-library-v4
    //         The reason why we differentiate between versions instead of just using context.startActivity
    //         for all devices is because in API 11 the recommended conventions for app navigation using
    //         the back key changed.
    //         */
    //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    //            TaskStackBuilderHelper.startActivities(context, cls, activityIntent);
    //        } else {
    //            context.startActivity(activityIntent);
    //        }

    // The task stack builder approach causes only the title and a white (blank) screen 
    // to be shown when the app is in the foreground and the push notification is 
    // opened (see also problem report to CN1 support forum: https://groups.google.com/d/msg/codenameone-discussions/Z3F924j_BG4/7rn7v7oABwAJ)
    // As a result, the context.startActivity() approach is currently taken always.
    // Not sure yet if it has any undesirable side effects for sdk version 
    // before JELLY_BEAN (actually HONEYCOMB (v3.0) according to TaskStackBuilder documentation 
    // at: http://developer.android.com/reference/android/support/v4/app/TaskStackBuilder.html.
    context.startActivity(activityIntent);
}

From source file:com.devspark.sidenavigation.meiriyiwen.MainActivity.java

/**
 * Start activity from SideNavigation./*from   w  w w .j  av a2s. c o m*/
 * 
 * @param title title of Activity
 * @param resId resource if of background image
 */
private void invokeActivity(String title, int resId) {
    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra(EXTRA_TITLE, title);
    intent.putExtra(EXTRA_RESOURCE_ID, resId);
    intent.putExtra(EXTRA_MODE, sideNavigationView.getMode() == Mode.LEFT ? 0 : 1);

    // 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.
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    startActivity(intent);
    // no animation of transition
    overridePendingTransition(0, 0);
}

From source file:com.airbop.client.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from   w w w.ja  v  a  2s  .c  o m*/
private static void generateNotification(Context context, String title, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if ((title == null) || (title.equals(""))) {
        title = context.getString(R.string.app_name);
    }
    Intent notificationIntent = new Intent(context, DemoActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    Notification notification = new NotificationCompat.Builder(context).setContentTitle(title)
            .setContentText(message).setContentIntent(intent).setSmallIcon(icon).setWhen(when)
            .setStyle(new NotificationCompat.BigTextStyle().bigText(message)).build();

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}

From source file:com.capstonecontrol.AccountsActivity.java

/**
 * Sets up the 'connect' screen content.
 *//*ww  w. j av  a  2s. com*/
private void setConnectScreenContent() {
    List<String> accounts = getGoogleAccounts();
    if (accounts.size() == 0) {
        // Show a dialog and invoke the "Add Account" activity if requested
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage(R.string.needs_account);
        builder.setPositiveButton(R.string.add_account, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                startActivity(new Intent(Settings.ACTION_ADD_ACCOUNT));
            }
        });
        builder.setNegativeButton(R.string.skip, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setIcon(android.R.drawable.stat_sys_warning);
        builder.setTitle(R.string.attention);
        builder.show();
    } else {
        final ListView listView = (ListView) findViewById(R.id.select_account);
        listView.setAdapter(new ArrayAdapter<String>(mContext, R.layout.account, accounts));
        listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        listView.setItemChecked(mAccountSelectedPosition, true);

        final Button connectButton = (Button) findViewById(R.id.connect);
        connectButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                CapstoneControlActivity.userChanged = true;
                // Set "connecting" status
                SharedPreferences prefs = Util.getSharedPreferences(mContext);
                prefs.edit().putString(Util.CONNECTION_STATUS, Util.CONNECTING).commit();
                // Get account name
                mAccountSelectedPosition = listView.getCheckedItemPosition();
                TextView account = (TextView) listView.getChildAt(mAccountSelectedPosition);
                // Register
                register((String) account.getText());
                // finish();
                // clear the module list so that a new one will get found
                CapstoneControlActivity.modules.clear();
                // instead of finish() go back to the AccountsActivity for
                // new login.
                CapstoneControlActivity.googleUserName = (String) account.getText();
                Intent myIntent = new Intent(v.getContext(), SplashActivity.class);
                startActivity(myIntent);
                myIntent = new Intent(v.getContext(), CapstoneControlActivity.class);
                startActivity(myIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
            }
        });
    }
}

From source file:ar.com.martinrevert.argenteam.GcmIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from   ww w. j  a v a2s  .  co  m*/
private void generarNotification(Context context, String message, String urlimagen, String urlarticulo,
        String tipo, String fecha) {
    SharedPreferences preferencias = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    boolean vib = preferencias.getBoolean("vibraoff", false);
    boolean movieoff = preferencias.getBoolean("movieoff", false);
    boolean tvoff = preferencias.getBoolean("tvoff", false);
    String ringmovie = preferencias.getString("prefRingtonemovie", "");
    String ringtv = preferencias.getString("prefRingtonetv", "");
    //Todo traducir ticker
    String ticker = "Nuevo subttulo " + tipo + " en aRGENTeaM";

    Random randomGenerator = new Random();
    int randomInt = randomGenerator.nextInt(100);

    Bitmap bitmap = getRemoteImage(urlimagen, tipo);

    Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

    int dash = 500;
    int short_gap = 200;

    long[] pattern = { 0, // Start immediately
            dash, short_gap, dash, short_gap, dash };

    Intent notificationIntent;
    String ringtone;
    int ledlight;

    if (tipo.equalsIgnoreCase("Movie")) {
        ringtone = ringmovie;
        notificationIntent = new Intent(context, Peli.class);
        ledlight = preferencias.getInt("ledMovie", 0);

    } else {
        notificationIntent = new Intent(context, Tv.class);
        ringtone = ringtv;
        ledlight = preferencias.getInt("ledTV", 0);
        System.out.println(ledlight);
    }
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("passed", urlarticulo);

    PendingIntent pendingIntent;

    pendingIntent = PendingIntent.getActivity(context, randomInt, notificationIntent, 0);

    Notification myNotification;
    myNotification = new NotificationCompat.Builder(context).setPriority(1).setContentTitle(message)
            .setTicker(ticker).setLights(ledlight, 300, 300).setWhen(System.currentTimeMillis())
            .setContentIntent(pendingIntent).setSound(Uri.parse(ringtone)).setAutoCancel(true)
            .setSmallIcon(R.drawable.ic_stat_ic_argenteam_gcm).build();

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        RemoteViews views;
        views = new RemoteViews(getPackageName(), R.layout.custom_notification);
        views.setImageViewBitmap(R.id.big_picture, bitmap);
        views.setImageViewBitmap(R.id.big_icon,
                BitmapFactory.decodeResource(getResources(), R.drawable.ic_stat_ic_argenteam_gcm));
        views.setTextViewText(R.id.title, message);
        myNotification.bigContentView = views;
    }

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

    if (movieoff && tipo.equalsIgnoreCase("Movie")) {
        if (vib) {
            v.vibrate(pattern, -1);
        }
        notificationManager.notify(randomInt, myNotification);

    }

    if (tvoff && tipo.equalsIgnoreCase("Serie TV")) {
        if (vib) {
            v.vibrate(pattern, -1);
        }
        notificationManager.notify(randomInt, myNotification);

    }

}

From source file:fr.gotorennes.AbstractMapActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.accueil:
        goToRennes.trackEvent("Menu", "Accueil");
        Intent intentAccueil = new Intent(getApplicationContext(), GoToRennesActivity.class);
        intentAccueil.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentAccueil);/*  ww  w . j a  v a 2s  .c om*/
        return true;
    case R.id.quitter:
        goToRennes.trackEvent("Menu", "Quitter");
        logout();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:net.openid.appauth.AuthorizationManagementActivity.java

/**
 * Creates an intent to handle the completion of an authorization flow. This restores
 * the original AuthorizationManagementActivity that was created at the start of the flow.
 * @param context the package context for the app.
 * @param responseUri the response URI, which carries the parameters describing the response.
 *///from  w  w  w.ja  v a  2 s.  c o m
public static Intent createResponseHandlingIntent(Context context, Uri responseUri) {
    Intent intent = createBaseIntent(context);
    intent.setData(responseUri);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    return intent;
}

From source file:com.battlelancer.seriesguide.appwidget.ListWidgetProvider.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public static RemoteViews buildRemoteViews(Context context, AppWidgetManager appWidgetManager,
        int appWidgetId) {
    // setup intent pointing to RemoteViewsService providing the views for the collection
    Intent intent = new Intent(context, ListWidgetService.class);
    intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    // When intents are compared, the extras are ignored, so we need to
    // embed the extras into the data so that the extras will not be
    // ignored.// w ww.  j  av  a 2s  .  com
    intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));

    // determine layout (current size) and theme (user pref)
    final boolean isCompactLayout = isCompactLayout(appWidgetManager, appWidgetId);
    final boolean isLightTheme = WidgetSettings.isLightTheme(context, appWidgetId);
    int layoutResId;
    if (isLightTheme) {
        layoutResId = isCompactLayout ? R.layout.appwidget_v11_light_compact : R.layout.appwidget_v11_light;
    } else {
        layoutResId = isCompactLayout ? R.layout.appwidget_v11_compact : R.layout.appwidget_v11;
    }

    // build widget views
    RemoteViews rv = new RemoteViews(context.getPackageName(), layoutResId);
    rv.setRemoteAdapter(R.id.list_view, intent);
    // The empty view is displayed when the collection has no items. It
    // should be a sibling of the collection view.
    rv.setEmptyView(R.id.list_view, R.id.empty_view);

    // set the background color
    int bgColor = WidgetSettings.getWidgetBackgroundColor(context, appWidgetId, isLightTheme);
    rv.setInt(R.id.container, "setBackgroundColor", bgColor);

    // determine type specific values
    final int widgetType = WidgetSettings.getWidgetListType(context, appWidgetId);
    int showsTabIndex;
    int titleResId;
    int emptyResId;
    if (widgetType == WidgetSettings.Type.UPCOMING) {
        // upcoming
        showsTabIndex = ShowsActivity.InitBundle.INDEX_TAB_UPCOMING;
        titleResId = R.string.upcoming;
        emptyResId = R.string.noupcoming;
    } else if (widgetType == WidgetSettings.Type.RECENT) {
        // recent
        showsTabIndex = ShowsActivity.InitBundle.INDEX_TAB_RECENT;
        titleResId = R.string.recent;
        emptyResId = R.string.norecent;
    } else {
        // favorites
        showsTabIndex = ShowsActivity.InitBundle.INDEX_TAB_SHOWS;
        titleResId = R.string.action_shows_filter_favorites;
        emptyResId = R.string.no_nextepisode;
    }

    // change title and empty view based on type
    rv.setTextViewText(R.id.empty_view, context.getString(emptyResId));
    if (!isCompactLayout) {
        // only regular layout has text title
        rv.setTextViewText(R.id.widgetTitle, context.getString(titleResId));
    }

    // app launch button
    final Intent appLaunchIntent = new Intent(context, ShowsActivity.class)
            .putExtra(ShowsActivity.InitBundle.SELECTED_TAB, showsTabIndex);
    PendingIntent pendingIntent = TaskStackBuilder.create(context).addNextIntent(appLaunchIntent)
            .getPendingIntent(appWidgetId, PendingIntent.FLAG_UPDATE_CURRENT);
    rv.setOnClickPendingIntent(R.id.widget_title, pendingIntent);

    // item intent template, launches episode detail view
    TaskStackBuilder builder = TaskStackBuilder.create(context);
    builder.addNextIntent(appLaunchIntent);
    builder.addNextIntent(new Intent(context, EpisodesActivity.class));
    rv.setPendingIntentTemplate(R.id.list_view, builder.getPendingIntent(1, PendingIntent.FLAG_UPDATE_CURRENT));

    // settings button
    Intent settingsIntent = new Intent(context, ListWidgetConfigure.class)
            .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
            .putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    rv.setOnClickPendingIntent(R.id.widget_settings,
            PendingIntent.getActivity(context, appWidgetId, settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT));

    return rv;
}

From source file:au.com.websitemasters.schools.lcps.push.MyGcmListenerService.java

/**
 * Create and show a simple notification containing the received GCM message.
 *
 * @param message GCM message received./*w  ww .jav  a2 s.  co m*/
 */

public void sendNotification(String message, Class clas) {

    //load not readed. +1. save em.
    int notReaded = ((SchoolsApplication) getApplicationContext()).loadBadgesCount();
    notReaded++;
    ((SchoolsApplication) getApplicationContext()).saveBadgesCount(notReaded);

    //show it on badge.
    ShortcutBadger.applyCount(getApplicationContext(), notReaded);

    Intent intent = new Intent(this, clas);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.logo_gray).setContentTitle("Leschenault Catholic Primary School")
            .setContentText(message).setAutoCancel(true).setNumber(notReaded).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());

    //push realtime refresh of lists (ANN)
    Intent intentBroadcast = new Intent(BROADCAST_ACTION);
    sendBroadcast(intentBroadcast);
}

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

private void sendNotification(String msg, String senderID) {
    mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(this, MainActivity.class);
    intent.putExtra(MainActivity.EXTRA_NOTIFICATION_RETRIEVE, senderID);
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    notificationCounter++;// w ww.j a v  a 2  s  .  co m

    if (messages.size() > 1) {
        msg = msg + "...";
    }

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
            .setVibrate(new long[] { 0, 500, 250, 500, 250 }).setLights(Color.BLUE, 200, 200)
            .setSmallIcon(R.drawable.logo).setContentTitle("Let's Chat Notification")
            .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)).setNumber(notificationCounter)
            .setTicker(msg).setContentText(msg);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    // Sets a title for the Inbox style big view
    inboxStyle.setBigContentTitle("Unread messages (" + notificationCounter + "):");
    // Moves events into the big view
    ArrayList<String> temp = new ArrayList<String>();
    for (int i = 0; i < 5; ++i) {
        if (i == messages.size()) {
            break;
        }
        temp.add(messages.get(i));
    }
    Collections.reverse(temp);
    messages = temp;
    for (String s : messages) {
        inboxStyle.addLine(s);
    }

    mBuilder.setStyle(inboxStyle);

    mBuilder.setAutoCancel(true);
    mBuilder.setContentIntent(contentIntent);
    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    //        AwesomeAdapter.animate = true;
}