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:net.kourlas.voipms_sms.Notifications.java

public void showNotifications(List<String> contacts) {
    if (!(ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationsActivity)) {
        Conversation[] conversations = Database.getInstance(applicationContext)
                .getConversations(preferences.getDid());
        for (Conversation conversation : conversations) {
            if (!conversation.isUnread() || !contacts.contains(conversation.getContact())
                    || (ActivityMonitor.getInstance().getCurrentActivity() instanceof ConversationActivity
                            && ((ConversationActivity) ActivityMonitor.getInstance().getCurrentActivity())
                                    .getContact().equals(conversation.getContact()))) {
                continue;
            }//  w ww .j  a  v  a2s. co  m

            String smsContact = Utils.getContactName(applicationContext, conversation.getContact());
            if (smsContact == null) {
                smsContact = Utils.getFormattedPhoneNumber(conversation.getContact());
            }

            String allSmses = "";
            String mostRecentSms = "";
            boolean initial = true;
            for (Message message : conversation.getMessages()) {
                if (message.getType() == Message.Type.INCOMING && message.isUnread()) {
                    if (initial) {
                        allSmses = message.getText();
                        mostRecentSms = message.getText();
                        initial = false;
                    } else {
                        allSmses = message.getText() + "\n" + allSmses;
                    }
                } else {
                    break;
                }
            }

            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(applicationContext);

            notificationBuilder.setContentTitle(smsContact);
            notificationBuilder.setContentText(mostRecentSms);
            notificationBuilder.setSmallIcon(R.drawable.ic_chat_white_24dp);
            notificationBuilder.setPriority(Notification.PRIORITY_HIGH);
            notificationBuilder
                    .setSound(Uri.parse(Preferences.getInstance(applicationContext).getNotificationSound()));
            notificationBuilder.setLights(0xFFAA0000, 1000, 5000);
            if (Preferences.getInstance(applicationContext).getNotificationVibrateEnabled()) {
                notificationBuilder.setVibrate(new long[] { 0, 250, 250, 250 });
            } else {
                notificationBuilder.setVibrate(new long[] { 0 });
            }
            notificationBuilder.setColor(0xFFAA0000);
            notificationBuilder.setAutoCancel(true);
            notificationBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(allSmses));

            Bitmap largeIconBitmap;
            try {
                largeIconBitmap = MediaStore.Images.Media.getBitmap(applicationContext.getContentResolver(),
                        Uri.parse(Utils.getContactPhotoUri(applicationContext, conversation.getContact())));
                largeIconBitmap = Bitmap.createScaledBitmap(largeIconBitmap, 256, 256, false);
                largeIconBitmap = Utils.applyCircularMask(largeIconBitmap);
                notificationBuilder.setLargeIcon(largeIconBitmap);
            } catch (Exception ignored) {

            }

            Intent intent = new Intent(applicationContext, ConversationActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(applicationContext);
            stackBuilder.addParentStack(ConversationActivity.class);
            stackBuilder.addNextIntent(intent);
            notificationBuilder
                    .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT));

            Intent replyIntent = new Intent(applicationContext, ConversationQuickReplyActivity.class);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
            } else {
                //noinspection deprecation
                replyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
            }
            replyIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent replyPendingIntent = PendingIntent.getActivity(applicationContext, 0, replyIntent,
                    PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder replyAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_reply_white_24dp,
                    applicationContext.getString(R.string.notifications_button_reply), replyPendingIntent);
            notificationBuilder.addAction(replyAction.build());

            Intent markAsReadIntent = new Intent(applicationContext, MarkAsReadReceiver.class);
            markAsReadIntent.putExtra(applicationContext.getString(R.string.conversation_extra_contact),
                    conversation.getContact());
            PendingIntent markAsReadPendingIntent = PendingIntent.getBroadcast(applicationContext, 0,
                    markAsReadIntent, PendingIntent.FLAG_CANCEL_CURRENT);
            NotificationCompat.Action.Builder markAsReadAction = new NotificationCompat.Action.Builder(
                    R.drawable.ic_drafts_white_24dp,
                    applicationContext.getString(R.string.notifications_button_mark_read),
                    markAsReadPendingIntent);
            notificationBuilder.addAction(markAsReadAction.build());

            int id;
            if (notificationIds.get(conversation.getContact()) != null) {
                id = notificationIds.get(conversation.getContact());
            } else {
                id = notificationIdCount++;
                notificationIds.put(conversation.getContact(), id);
            }
            NotificationManager notificationManager = (NotificationManager) applicationContext
                    .getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, notificationBuilder.build());
        }
    }
}

From source file:com.jeremyhaberman.playgrounds.WebPlaygroundDAO.java

@Override
public Collection<Playground> getAll(Context context) {
    // synchronized (Swingset.initPlaygroundLock) {
    playgrounds = new ArrayList<Playground>();
    String result = swingset.getResources().getString(R.string.error);
    HttpURLConnection httpConnection = null;
    Log.d(TAG, "getPlaygrounds()");

    try {/*from  w w  w . ja v  a2  s.co  m*/
        // Check if task has been interrupted
        if (Thread.interrupted()) {
            throw new InterruptedException();
        }

        // Build query
        URL url = new URL("http://swingsetweb.appspot.com/playground");
        httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.setConnectTimeout(15000);
        httpConnection.setReadTimeout(15000);
        StringBuilder response = new StringBuilder();

        if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // Read results from the query
            BufferedReader input = new BufferedReader(
                    new InputStreamReader(httpConnection.getInputStream(), "UTF-8"));
            String strLine = null;
            while ((strLine = input.readLine()) != null) {
                response.append(strLine);
            }
            input.close();

        }

        // Parse to get translated text
        JSONArray jsonPlaygrounds = new JSONArray(response.toString());
        int numOfPlaygrounds = jsonPlaygrounds.length();

        JSONObject jsonPlayground = null;

        for (int i = 0; i < numOfPlaygrounds; i++) {
            jsonPlayground = jsonPlaygrounds.getJSONObject(i);
            playgrounds.add(toPlayground(jsonPlayground));
        }

    } catch (Exception e) {
        Log.e(TAG, "Exception", e);
        Intent errorIntent = new Intent(context, Playgrounds.class);
        errorIntent.putExtra("Exception", e.getLocalizedMessage());
        errorIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(errorIntent);
    } finally {
        if (httpConnection != null) {
            httpConnection.disconnect();
        }
    }

    // all done
    Log.d(TAG, "   -> returned " + result);
    return playgrounds;
    // }
}

From source file:jp.maju.wifiserver.client.ClientActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_client_connect:
        doConnect2Server();//w  w w  . ja v a 2  s  .c o m
        break;
    case R.id.menu_client_disconnect:
        onDisabling();
        break;
    case android.R.id.home:
        startActivity(new Intent(this, GateActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
        finish();
        break;
    }

    return true;
}

From source file:no.ntnu.idi.socialhitchhiking.utility.ShareOnFacebook.java

/**
 * Action for do not share button. When pressed application goes back to main and deletes activity stack.
 * @param button/*from  w w  w .j  a  v a2 s .co m*/
 */
public void doNotShare(View button) {
    Intent intent = new Intent(ShareOnFacebook.this, Main.class);
    startActivity(intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
    showToast("Trip created");
    finish();
}

From source file:com.aniruddhc.acemusic.player.Dialogs.CustomizeScreensDialog.java

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    parentActivity = getActivity();//  w  w  w.  j a v a  2 s .  c  om
    dialogFragment = (DialogFragment) getFragmentManager().findFragmentByTag("customizeScreensDialog");

    sharedPreferences = parentActivity.getSharedPreferences("com.aniruddhc.acemusic.player",
            Context.MODE_PRIVATE);

    rootView = (View) parentActivity.getLayoutInflater().inflate(R.layout.customize_screens_layout, null);

    customizeScreensText = (TextView) rootView.findViewById(R.id.customize_screens_text);
    customizeScreensText.setTypeface(TypefaceHelper.getTypeface(parentActivity, "RobotoCondensed-Light"));
    customizeScreensText.setPaintFlags(
            customizeScreensText.getPaintFlags() | Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG);

    //Populate the arraylists with the settings saved in SharedPreferences.
    page1 = sharedPreferences.getString("PAGE_1", getResources().getString(R.string.artists_caps));
    page2 = sharedPreferences.getString("PAGE_2", getResources().getString(R.string.albums_caps));
    page3 = sharedPreferences.getString("PAGE_3", getResources().getString(R.string.songs_caps));
    page4 = sharedPreferences.getString("PAGE_4", getResources().getString(R.string.playlists_caps));
    page5 = sharedPreferences.getString("PAGE_5", getResources().getString(R.string.genres_caps));
    page6 = sharedPreferences.getString("PAGE_6", getResources().getString(R.string.folders_caps));

    if (!page1.equals("null") || !page1.equals(null)) {
        screenTitlesList.add(page1);
    }

    if (!page2.equals("null") || !page2.equals(null)) {
        screenTitlesList.add(page2);
    }

    if (!page3.equals("null") || !page3.equals(null)) {
        screenTitlesList.add(page3);
    }

    if (!page4.equals("null") || !page4.equals(null)) {
        screenTitlesList.add(page4);
    }

    if (!page5.equals("null") || !page5.equals(null)) {
        screenTitlesList.add(page5);
    }

    if (!page6.equals("null") || !page6.equals(null)) {
        screenTitlesList.add(page6);
    }

    listView = (DragSortListView) rootView.findViewById(R.id.customize_screens_listview);
    adapter = new CustomizeScreensListAdapter(parentActivity, screenTitlesList);
    listView.setAdapter(adapter);
    listView.setDropListener(onDrop);
    SimpleFloatViewManager simpleFloatViewManager = new SimpleFloatViewManager(listView);
    simpleFloatViewManager.setBackgroundColor(Color.TRANSPARENT);
    listView.setFloatViewManager(simpleFloatViewManager);

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

    //Set the dialog title.
    builder.setTitle(R.string.customize_screens);
    builder.setView(rootView);
    builder.setPositiveButton(R.string.done, new OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {
            dialogFragment.dismiss();

            //adapter.getItem(i) will get us the order for the screens.
            sharedPreferences.edit().putString("PAGE_1", adapter.getItem(0).toString().toUpperCase()).commit();
            sharedPreferences.edit().putString("PAGE_2", adapter.getItem(1).toString().toUpperCase()).commit();
            sharedPreferences.edit().putString("PAGE_3", adapter.getItem(2).toString().toUpperCase()).commit();
            sharedPreferences.edit().putString("PAGE_4", adapter.getItem(3).toString().toUpperCase()).commit();
            sharedPreferences.edit().putString("PAGE_5", adapter.getItem(4).toString().toUpperCase()).commit();
            sharedPreferences.edit().putString("PAGE_6", adapter.getItem(5).toString().toUpperCase()).commit();

            Toast.makeText(parentActivity, R.string.changes_saved, Toast.LENGTH_SHORT).show();

            //Restart the app.
            Intent i = parentActivity.getBaseContext().getPackageManager()
                    .getLaunchIntentForPackage(parentActivity.getBaseContext().getPackageName());

            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            dialogFragment.dismiss();
            getActivity().finish();
            startActivity(i);

        }

    });

    return builder.create();
}

From source file:com.josecarlos.couplecounters.LoginActivity.java

public void navigatetoRegisterActivity(View view) {
    Intent loginIntent = new Intent(getApplicationContext(), RegisterActivity.class);
    loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(loginIntent);// w w w.  j a  v  a  2  s . c  o  m
}

From source file:com.example.gemswin.screencastrecevertest.MainActivity_Reciever.java

 @Override
protected void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.activity_main_reciever);
   WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);
   String ip = Formatter.formatIpAddress(wm.getConnectionInfo().getIpAddress());
   TextView text = (TextView) findViewById(R.id.textView);


   planetList = new ArrayList<String>();

   mTextureView = (TextureView)findViewById(R.id.textureView);
   mTextureView.setSurfaceTextureListener(this);
   mTextureView.requestLayout();/* ww w . ja v a2s  . c o  m*/
   mTextureView.invalidate();
   mTextureView.setOpaque(false);
   logout = (Button) findViewById(R.id.logout);
   cast = (Button) findViewById(R.id.castAsmaster);


   doubtbutton = (Button) findViewById(R.id.doubt);
   viewbutton = (Button) findViewById(R.id.viewdoubt);

   pref = new PrefManager(getApplicationContext());
   text.setText(ip);
   logout.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         pref.logout();
         Intent i = new Intent(MainActivity_Reciever.this, LoginActivity.class);
         startActivity(i);
         finish();
      }
   });
   cast.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {

         new allowcast().execute();
      }
   });
   viewbutton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         //pref.logout();                                               // LOOK HERE ASH
         /*Intent i = new Intent(MainActivity_Reciever.this,DoubtActivity.class);
         startActivity(i);*/
         new viewdoubttask().execute();


      }
   });

   doubtbutton.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
         //pref.logout();                                               // LOOK HERE ASH
         /*Intent i = new Intent(MainActivity_Reciever.this,DoubtActivity.class);
         startActivity(i);*/
         DoubtBox();

      }
   });

   mTask = new ReceiverAsyncTask(this);
   mTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

   Intent intent1 = new Intent(this, MyBroadcastReceiver.class);
   intent1.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
   PendingIntent pendingIntent = PendingIntent.getBroadcast(
         getApplicationContext(), 234324243, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
   AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
   alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (10 * 1000), pendingIntent);


}

From source file:com.amazon.cordova.plugin.ADMMessageHandler.java

/**
 * Creates a notification when app is not running or is not in foreground. It puts the message info into the Intent
 * extra/* w w  w  .ja va2s.  c  o m*/
 * 
 * @param context
 * @param extras
 */
public void createNotification(Context context, Bundle extras) {
    NotificationManager notificationManager = (NotificationManager) getSystemService(
            Context.NOTIFICATION_SERVICE);
    String appName = getAppName(this);

    // reuse the intent so that we can combine multiple messages into extra
    if (notificationIntent == null) {
        notificationIntent = new Intent(this, ADMHandlerActivity.class);
    }
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
    notificationIntent.putExtra("pushBundle", extras);

    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    final Builder notificationBuilder = new Notification.Builder(context);
    notificationBuilder.setSmallIcon(context.getApplicationInfo().icon).setWhen(System.currentTimeMillis())
            .setContentIntent(contentIntent);

    if (this.shouldShowMessageInNotification()) {
        String message = extras.getString(PushPlugin.MESSAGE);
        notificationBuilder.setContentText(Html.fromHtml(message).toString());
    } else {
        notificationBuilder.setContentText(this.defaultMessageTextInNotification());
    }

    String title = appName;
    notificationBuilder.setContentTitle(title).setTicker(title);
    notificationBuilder.setAutoCancel(true);
    // Because the ID remains unchanged, the existing notification is updated.
    notificationManager.notify((String) appName, NOTIFICATION_ID, notificationBuilder.getNotification());
}

From source file:fr.simon.marquis.preferencesmanager.ui.PreferencesActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        if (launchedFromShortcut) {
            Intent i = new Intent(this, AppListActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(i);//from  www  . ja v a  2 s  .co  m
        }
        finish();
        return true;
    case R.id.action_fav:
        Utils.setFavorite(packageName, !Utils.isFavorite(packageName, this), this);
        invalidateOptionsMenu();
        break;
    case R.id.action_shortcut:
        createShortcut();
        Toast.makeText(this, R.string.toast_shortcut, Toast.LENGTH_SHORT).show();
        break;
    default:
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.achow101.bitcointalkforum.MainActivity.java

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getSupportFragmentManager();

    switch (position) {
    // Home//from   w  w w  . j a v  a  2  s. c  om
    case 0:
        fragmentManager.beginTransaction().replace(R.id.container, HomeFragment.newInstance(sessId)).commit();
        break;
    // Unread posts
    case 1:
        fragmentManager.beginTransaction()
                .replace(R.id.container,
                        UnreadPostListsFragment
                                .newInstance("https://bitcointalk.org/index.php?action=unread;start=0", sessId))
                .commit();
        break;
    // New replies
    case 2:
        fragmentManager.beginTransaction()
                .replace(R.id.container,
                        UnreadPostListsFragment.newInstance(
                                "https://bitcointalk.org/index.php?action=unreadreplies;start=0", sessId))
                .commit();
        break;
    // Watchlist
    case 3:
        fragmentManager.beginTransaction()
                .replace(R.id.container, UnreadPostListsFragment
                        .newInstance("https://bitcointalk.org/index.php?action=watchlist;start=0", sessId))
                .commit();
        break;
    // Profile
    case 4:
        fragmentManager.beginTransaction().replace(R.id.container, ProfileFragment.newInstance(sessId))
                .commit();
        break;
    // Messages
    case 5:
        fragmentManager.beginTransaction().replace(R.id.container, MessagesFragment.newInstance(1, sessId))
                .commit();
        break;
    // Logout
    case 6:
        sessId = null;
        Intent intentLogout = new Intent(this, LoginActivity.class);
        intentLogout.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intentLogout);
        finish();
        break;
    }

}