Example usage for android.content Intent FLAG_ACTIVITY_CLEAR_TASK

List of usage examples for android.content Intent FLAG_ACTIVITY_CLEAR_TASK

Introduction

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

Prototype

int FLAG_ACTIVITY_CLEAR_TASK

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

Click Source Link

Document

If set in an Intent passed to Context#startActivity Context.startActivity() , this flag will cause any existing task that would be associated with the activity to be cleared before the activity is started.

Usage

From source file:com.openarc.nirmal.mytrack.AttendanceActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch (item.getItemId()) {
    case R.id.menu_about:
        AboutDialog();//from   www.ja v  a 2s  .  c om
        break;
    case R.id.menu_logout:
        Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:yyx.com.project3.gcm.MyGcmPushReceiver.java

/**
 * Showing notification with text only/* w w  w. j a v  a  2  s.co  m*/
 * */
private void showNotificationMessage(Context context, String title, String message, String timeStamp,
        Intent intent) {
    notificationUtils = new yyx.com.project3.gcm.NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent);
}

From source file:com.mobileman.moments.android.frontend.activity.IncomingCallActivity.java

private void sendNotificationAndFinish() {
    if (streamingUser != null) {
        Intent intent = new Intent(getApplicationContext(), MediaPlayerActivity.class);
        Bundle extras = new Bundle();
        extras.putString(MediaPlayerActivity.MEDIA_URL, streamingUser.getStream().getFullVideoUrl());
        extras.putString(MediaPlayerActivity.THUMBNAIL_URL, streamingUser.getStream().getFullThumbnailUrl());
        extras.putString(MediaPlayerActivity.USER_ID, streamingUser.getUuid());
        intent.putExtras(extras);/*from w w  w .  ja  v  a 2 s.c om*/
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
                | Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
        String notificationTitle = userName + " " + getResources().getString(R.string.isLiveSuffix);
        String notificationText = "";// getResources().getString(R.string.missedCallNotification) + " " + streamingUser.getName();
        String mediaUrl = streamingUser.getStream().getFullVideoUrl();

        if ((streamingUser.getStream() != null) && (streamingUser.getStream().getTitle() != null)) {
            notificationText = streamingUser.getStream().getTitle(); //notificationText + "(" + streamingUser.getStream().getTitle() + ")";
        }
        ImageView incomingCallUserImageView = (ImageView) findViewById(R.id.incomingCallUserImageView);
        Bitmap bitmap = ((BitmapDrawable) incomingCallUserImageView.getDrawable()).getBitmap();
        NotificationCompat.BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle();
        b.setAutoCancel(true).setSmallIcon(R.drawable.ic_launcher).setDefaults(Notification.DEFAULT_ALL)
                .setWhen(System.currentTimeMillis()).setTicker("X").setContentTitle(notificationTitle)
                .setContentText(notificationText)
                .setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_SOUND)
                .setContentIntent(contentIntent);
        //            if (bitmap != null) {
        //                b.setLargeIcon(bitmap);
        //            }

        NotificationManager notificationManager = (NotificationManager) getApplicationContext()
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(++NOTIFICATION_COUNTER, b.build());

    }
    finish();
}

From source file:com.android.prachat.gcm.MyGcmPushReceiver.java

/**
 * Showing notification with text and image
 * *//*from   w  w w .j  a  va 2  s. c o m*/
private void showNotificationMessageWithBigImage(Context context, String title, String message,
        String timeStamp, Intent intent, String imageUrl) {
    notificationUtils = new NotificationUtils(context);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    notificationUtils.showNotificationMessage(title, message, timeStamp, intent, imageUrl);
}

From source file:de.elanev.studip.android.app.backend.net.oauth.SignInFragment.java

/**
 * Starts the next activity after prefetching.
 *///ww w  . j av a  2s .  c  om
public void startMainActivity() {
    Intent intent = new Intent(getActivity(), MainActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);

    Log.i(TAG, "Starting news Activity...");
    if (!ApiUtils.isOverApi11()) {
        getActivity().finish();
    }
}

From source file:com.example.android.wearable.wear.wearnotifications.MainActivity.java

private void generateBigTextStyleNotification() {

    Log.d(TAG, "generateBigTextStyleNotification()");

    // Main steps for building a BIG_TEXT_STYLE notification:
    //      0. Get your data
    //      1. Build the BIG_TEXT_STYLE
    //      2. Set up main Intent for notification
    //      3. Create additional Actions for the Notification
    //      4. Build and issue the notification

    // 0. Get your data (everything unique per Notification)
    MockDatabase.BigTextStyleReminderAppData bigTextStyleReminderAppData = MockDatabase.getBigTextStyleData();

    // 1. Build the BIG_TEXT_STYLE
    BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
            // Overrides ContentText in the big form of the template
            .bigText(bigTextStyleReminderAppData.getBigText())
            // Overrides ContentTitle in the big form of the template
            .setBigContentTitle(bigTextStyleReminderAppData.getBigContentTitle())
            // Summary line after the detail section in the big form of the template
            // Note: To improve readability, don't overload the user with info. If Summary Text
            // doesn't add critical information, you should skip it.
            .setSummaryText(bigTextStyleReminderAppData.getSummaryText());

    // 2. Set up main Intent for notification
    Intent notifyIntent = new Intent(this, BigTextMainActivity.class);

    // When creating your Intent, you need to take into account the back state, i.e., what
    // happens after your Activity launches and the user presses the back button.

    // There are two options:
    //      1. Regular activity - You're starting an Activity that's part of the application's
    //      normal workflow.

    //      2. Special activity - The user only sees this Activity if it's started from a
    //      notification. In a sense, the Activity extends the notification by providing
    //      information that would be hard to display in the notification itself.

    // For the BIG_TEXT_STYLE notification, we will consider the activity launched by the main
    // Intent as a special activity, so we will follow option 2.

    // For an example of option 1, check either the MESSAGING_STYLE or BIG_PICTURE_STYLE
    // examples.// w  w w.j a  v  a  2 s.c om

    // For more information, check out our dev article:
    // https://developer.android.com/training/notify-user/navigation.html

    // Sets the Activity to start in a new, empty task
    notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

    PendingIntent notifyPendingIntent = PendingIntent.getActivity(this, 0, notifyIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    // 3. Create additional Actions (Intents) for the Notification

    // In our case, we create two additional actions: a Snooze action and a Dismiss action
    // Snooze Action
    Intent snoozeIntent = new Intent(this, BigTextIntentService.class);
    snoozeIntent.setAction(BigTextIntentService.ACTION_SNOOZE);

    PendingIntent snoozePendingIntent = PendingIntent.getService(this, 0, snoozeIntent, 0);
    NotificationCompat.Action snoozeAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_alarm_white_48dp, "Snooze", snoozePendingIntent).build();

    // Dismiss Action
    Intent dismissIntent = new Intent(this, BigTextIntentService.class);
    dismissIntent.setAction(BigTextIntentService.ACTION_DISMISS);

    PendingIntent dismissPendingIntent = PendingIntent.getService(this, 0, dismissIntent, 0);
    NotificationCompat.Action dismissAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_cancel_white_48dp, "Dismiss", dismissPendingIntent).build();

    // 4. Build and issue the notification

    // Because we want this to be a new notification (not updating a previous notification), we
    // create a new Builder. Later, we use the same global builder to get back the notification
    // we built here for the snooze action, that is, canceling the notification and relaunching
    // it several seconds later.

    NotificationCompat.Builder notificationCompatBuilder = new NotificationCompat.Builder(
            getApplicationContext());

    GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);

    Notification notification = notificationCompatBuilder
            // BIG_TEXT_STYLE sets title and content for API 16 (4.1 and after)
            .setStyle(bigTextStyle)
            // Title for API <16 (4.0 and below) devices
            .setContentTitle(bigTextStyleReminderAppData.getContentTitle())
            // Content for API <24 (7.0 and below) devices
            .setContentText(bigTextStyleReminderAppData.getContentText()).setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_alarm_white_48dp))
            .setContentIntent(notifyPendingIntent)
            // Set primary color (important for Wear 2.0 Notifications)
            .setColor(getResources().getColor(R.color.colorPrimary))

            // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
            // devices and all Android Wear devices. If you have more than one notification and
            // you prefer a different summary notification, set a group key and create a
            // summary notification via
            // .setGroupSummary(true)
            // .setGroup(GROUP_KEY_YOUR_NAME_HERE)

            .setCategory(Notification.CATEGORY_REMINDER).setPriority(Notification.PRIORITY_HIGH)

            // Shows content on the lock-screen
            .setVisibility(Notification.VISIBILITY_PUBLIC)

            // Adds additional actions specified above
            .addAction(snoozeAction).addAction(dismissAction)

            .build();

    mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
}

From source file:cat.ereza.customactivityoncrash.CustomActivityOnCrash.java

/**
 * Installs CustomActivityOnCrash on the application using the default error activity.
 *
 * @param context Context to use for obtaining the ApplicationContext. Must not be null.
 *//*from www.j  a va 2 s. co m*/
public static void install(Context context) {
    try {
        if (context == null) {
            Log.e(TAG, "Install failed: context is null!");
        } else {
            if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                Log.w(TAG,
                        "CustomActivityOnCrash will be installed, but may not be reliable in API lower than 14");
            }

            //INSTALL!
            final Thread.UncaughtExceptionHandler oldHandler = Thread.getDefaultUncaughtExceptionHandler();

            if (oldHandler != null && oldHandler.getClass().getName().startsWith(CAOC_HANDLER_PACKAGE_NAME)) {
                Log.e(TAG, "You have already installed CustomActivityOnCrash, doing nothing!");
            } else {
                if (oldHandler != null
                        && !oldHandler.getClass().getName().startsWith(DEFAULT_HANDLER_PACKAGE_NAME)) {
                    Log.e(TAG,
                            "IMPORTANT WARNING! You already have an UncaughtExceptionHandler, are you sure this is correct? If you use ACRA, Crashlytics or similar libraries, you must initialize them AFTER CustomActivityOnCrash! Installing anyway, but your original handler will not be called.");
                }

                application = (Application) context.getApplicationContext();

                //We define a default exception handler that does what we want so it can be called from Crashlytics/ACRA
                Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
                    @Override
                    public void uncaughtException(Thread thread, final Throwable throwable) {
                        Log.e(TAG,
                                "App has crashed, executing CustomActivityOnCrash's UncaughtExceptionHandler",
                                throwable);

                        if (hasCrashedInTheLastSeconds(application)) {
                            Log.e(TAG,
                                    "App already crashed in the last 2 seconds, not starting custom error activity because we could enter a restart loop. Are you sure that your app does not crash directly on init?",
                                    throwable);
                            if (oldHandler != null) {
                                oldHandler.uncaughtException(thread, throwable);
                                return;
                            }
                        } else {
                            setLastCrashTimestamp(application, new Date().getTime());

                            if (errorActivityClass == null) {
                                errorActivityClass = guessErrorActivityClass(application);
                            }

                            if (isStackTraceLikelyConflictive(throwable, errorActivityClass)) {
                                Log.e(TAG,
                                        "Your application class or your error activity have crashed, the custom activity will not be launched!");
                                if (oldHandler != null) {
                                    oldHandler.uncaughtException(thread, throwable);
                                    return;
                                }
                            } else if (launchErrorActivityWhenInBackground || !isInBackground) {

                                final Intent intent = new Intent(application, errorActivityClass);
                                StringWriter sw = new StringWriter();
                                PrintWriter pw = new PrintWriter(sw);
                                throwable.printStackTrace(pw);
                                String stackTraceString = sw.toString();

                                //Reduce data to 128KB so we don't get a TransactionTooLargeException when sending the intent.
                                //The limit is 1MB on Android but some devices seem to have it lower.
                                //See: http://developer.android.com/reference/android/os/TransactionTooLargeException.html
                                //And: http://stackoverflow.com/questions/11451393/what-to-do-on-transactiontoolargeexception#comment46697371_12809171
                                if (stackTraceString.length() > MAX_STACK_TRACE_SIZE) {
                                    String disclaimer = " [stack trace too large]";
                                    stackTraceString = stackTraceString.substring(0,
                                            MAX_STACK_TRACE_SIZE - disclaimer.length()) + disclaimer;
                                }

                                if (enableAppRestart && restartActivityClass == null) {
                                    //We can set the restartActivityClass because the app will terminate right now,
                                    //and when relaunched, will be null again by default.
                                    restartActivityClass = guessRestartActivityClass(application);
                                } else if (!enableAppRestart) {
                                    //In case someone sets the activity and then decides to not restart
                                    restartActivityClass = null;
                                }

                                String userLogString = "";
                                while (!userLogs.isEmpty()) {
                                    userLogString += userLogs.poll();
                                }

                                intent.putExtra(EXTRA_STACK_TRACE, stackTraceString);
                                intent.putExtra(EXTRA_USER_ACTION_TRACE, userLogString);
                                intent.putExtra(EXTRA_RESTART_ACTIVITY_CLASS, restartActivityClass);
                                intent.putExtra(EXTRA_SHOW_ERROR_DETAILS, showErrorDetails);
                                intent.putExtra(EXTRA_EVENT_LISTENER, eventListener);
                                intent.putExtra(EXTRA_IMAGE_DRAWABLE_ID, defaultErrorActivityDrawableId);
                                intent.setFlags(
                                        Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                if (eventListener != null) {
                                    eventListener.onLaunchErrorActivity();
                                }
                                application.startActivity(intent);
                            }
                        }
                        final Activity lastActivity = lastActivityCreated.get();
                        if (lastActivity != null) {
                            //We finish the activity, this solves a bug which causes infinite recursion.
                            //This is unsolvable in API<14, so beware!
                            //See: https://github.com/ACRA/acra/issues/42
                            lastActivity.finish();
                            lastActivityCreated.clear();
                        }
                        killCurrentProcess();
                    }
                });
                if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    application
                            .registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
                                int currentlyStartedActivities = 0;
                                DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);

                                @Override
                                public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                                    if (activity.getClass() != errorActivityClass) {
                                        // Copied from ACRA:
                                        // Ignore activityClass because we want the last
                                        // application Activity that was started so that we can
                                        // explicitly kill it off.
                                        lastActivityCreated = new WeakReference<>(activity);
                                    }
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " created\n");
                                }

                                @Override
                                public void onActivityStarted(Activity activity) {
                                    currentlyStartedActivities++;
                                    isInBackground = (currentlyStartedActivities == 0);
                                    //Do nothing
                                }

                                @Override
                                public void onActivityResumed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " resumed\n");
                                }

                                @Override
                                public void onActivityPaused(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " paused\n");
                                }

                                @Override
                                public void onActivityStopped(Activity activity) {
                                    //Do nothing
                                    currentlyStartedActivities--;
                                    isInBackground = (currentlyStartedActivities == 0);
                                }

                                @Override
                                public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                                    //Do nothing
                                }

                                @Override
                                public void onActivityDestroyed(Activity activity) {
                                    userLogs.add(dateFormat.format(new Date()) + " "
                                            + activity.getLocalClassName() + " destroyed\n");
                                }
                            });
                }

                Log.i(TAG, "CustomActivityOnCrash has been installed.");
            }
        }
    } catch (Throwable t) {
        Log.e(TAG,
                "An unknown error occurred while installing CustomActivityOnCrash, it may not have been properly initialized. Please report this as a bug if needed.",
                t);
    }
}

From source file:com.parse.f8.view.SignInActivity.java

public void finishActivity() {
    // Start an intent for the dispatch activity
    Intent intent = new Intent(SignInActivity.this, DispatchActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
    startActivity(intent);/*w  w w  .j a v a  2  s .  c o  m*/
}

From source file:ch.bfh.instacircle.NetworkActiveActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Intent intent = null;// ww  w  .  j  a  v  a2  s.com
    switch (item.getItemId()) {
    case R.id.display_qrcode:
        // displaying the QR code
        SharedPreferences preferences = getSharedPreferences(PREFS_NAME, 0);
        String config = preferences.getString("SSID", "N/A") + "||" + preferences.getString("password", "N/A");
        try {
            intent = new Intent("com.google.zxing.client.android.ENCODE");
            intent.putExtra("ENCODE_TYPE", "TEXT_TYPE");
            intent.putExtra("ENCODE_DATA", config);
            intent.putExtra("ENCODE_FORMAT", "QR_CODE");
            intent.putExtra("ENCODE_SHOW_CONTENTS", false);
            startActivity(intent);
        } catch (ActivityNotFoundException e) {

            // if the "Barcode Scanner" application is not installed ask the
            // user if he wants to install it
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("InstaCircle - Barcode Scanner Required");
            alertDialog.setMessage(
                    "In order to use this feature, the Application \"Barcode Scanner\" must be installed. Install now?");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    // redirect to Google Play
                    try {
                        startActivity(new Intent(Intent.ACTION_VIEW,
                                Uri.parse("market://details?id=com.google.zxing.client.android")));
                    } catch (Exception e) {
                        Log.d(TAG, "Unable to find market. User will have to install ZXing himself");
                    }
                }
            });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        }
        return true;

    case R.id.leave_network:

        // Display a confirm dialog asking whether really to leave
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Leave Network?");
        builder.setMessage("Do you really want to leave this conversation?");
        builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                if (isServiceRunning()) {
                    String identification = getSharedPreferences(PREFS_NAME, 0).getString("identification",
                            "N/A");
                    Message message = new Message(identification, Message.MSG_MSGLEAVE, identification,
                            NetworkDbHelper.getInstance(NetworkActiveActivity.this).getNextSequenceNumber());
                    Intent intent = new Intent("messageSend");
                    intent.putExtra("message", message);
                    LocalBroadcastManager.getInstance(NetworkActiveActivity.this).sendBroadcast(intent);
                } else {
                    NetworkDbHelper.getInstance(NetworkActiveActivity.this).closeConversation();
                    NotificationManager notificationManager = (NotificationManager) getSystemService(
                            Context.NOTIFICATION_SERVICE);
                    notificationManager.cancelAll();
                    Intent intent = new Intent(NetworkActiveActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                }
            }
        });
        builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                return;
            }
        });
        AlertDialog dialog = builder.create();
        dialog.show();

        return true;

    case R.id.write_nfc_tag:

        if (!nfcAdapter.isEnabled()) {

            // if nfc is available but deactivated ask the user whether he
            // wants to enable it. If yes, redirect to the settings.
            AlertDialog alertDialog = new AlertDialog.Builder(this).create();
            alertDialog.setTitle("InstaCircle - NFC needs to be enabled");
            alertDialog.setMessage("In order to use this feature, NFC must be enabled. Enable now?");
            alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Yes", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS));
                }
            });
            alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "No", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertDialog.show();
        } else {
            // display a progress dialog waiting for the NFC tag to be
            // tapped
            writeNfcEnabled = true;
            writeNfcTagDialog = new ProgressDialog(this);
            writeNfcTagDialog.setTitle("InstaCircle - Share Networkconfiguration with NFC Tag");
            writeNfcTagDialog.setMessage("Please tap a writeable NFC Tag on the back of your device...");
            writeNfcTagDialog.setCancelable(false);
            writeNfcTagDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            writeNfcEnabled = false;
                            dialog.dismiss();
                        }
                    });

            writeNfcTagDialog.show();
        }
    default:
        return super.onOptionsItemSelected(item);
    }
}

From source file:com.silentcircle.contacts.list.ShortcutIntentBuilder.java

private void createContactShortcutIntent(Uri contactUri, String contentType, String displayName,
        String lookupKey, byte[] bitmapData) {
    Drawable drawable = getPhotoDrawable(bitmapData, displayName, lookupKey);

    Intent shortcutIntent = new Intent(ContactsContract.QuickContact.ACTION_QUICK_CONTACT);

    // When starting from the launcher, start in a new, cleared task.
    // CLEAR_WHEN_TASK_RESET cannot reset the root of a task, so we
    // clear the whole thing preemptively here since QuickContactActivity will
    // finish itself when launching other detail activities. We need to use
    // Intent.FLAG_ACTIVITY_NO_ANIMATION since not all versions of launcher will respect
    // the INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION intent extra.
    shortcutIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK
            | Intent.FLAG_ACTIVITY_NO_ANIMATION);

    // Tell the launcher to not do its animation, because we are doing our own
    shortcutIntent.putExtra(INTENT_EXTRA_IGNORE_LAUNCH_ANIMATION, true);

    shortcutIntent.setDataAndType(contactUri, contentType);
    shortcutIntent.putExtra(ContactsContract.QuickContact.EXTRA_EXCLUDE_MIMES, (String[]) null);

    final Bitmap icon = generateQuickContactIcon(drawable);

    Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
    if (TextUtils.isEmpty(displayName)) {
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mContext.getResources().getString(R.string.missing_name));
    } else {/*from ww w.j  a  v a  2 s. c o m*/
        intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, displayName);
    }

    mListener.onShortcutIntentCreated(contactUri, intent);
}