Example usage for android.content Intent FLAG_ACTIVITY_SINGLE_TOP

List of usage examples for android.content Intent FLAG_ACTIVITY_SINGLE_TOP

Introduction

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

Prototype

int FLAG_ACTIVITY_SINGLE_TOP

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

Click Source Link

Document

If set, the activity will not be launched if it is already running at the top of the history stack.

Usage

From source file:com.poguico.palmabici.network.synchronizer.NetworkStationAlarm.java

public void showNotification(Station station) {
    SharedPreferences mPrefs;/*from   w ww. j a v a2s . c  om*/
    SharedPreferences.Editor edit;
    String message = Formatter.formatBikesAvailableMessage(context, station);
    Bitmap bigIcon = BitmapFactory.decodeResource(context.getResources(), R.drawable.palmabici_bw);
    Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                    | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK),
            PendingIntent.FLAG_ONE_SHOT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.bike)
            .setLargeIcon(bigIcon).setContentTitle("PalmaBici").setContentText(message)
            .setLights(0x0000ff00, 1000, 1000).setTicker(message).setSound(uri).setAutoCancel(true);

    NotificationManager mgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    mBuilder.setContentIntent(pendingIntent);

    mPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    edit = mPrefs.edit();
    edit.putInt(PREFS_SHOWN_STATION, station.getId());
    edit.commit();

    mgr.notify(0, mBuilder.build());
}

From source file:net.lp.hivawareness.v4.HIVAwarenessActivity.java

/** Called when the activity is first created. */
@Override//from  w w  w  . j a  va 2  s  .  c om
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity);

    //Save ApplicationContext
    applicationContext = this.getApplicationContext();

    enableStrictMode();

    if (DEBUG && mStrictModeAvailable) {
        StrictModeWrapper.allowThreadDiskWrites();//disables temporarily, reenables below
    }

    if (!DEBUG) {
        //BugSense uncaught exceptions analytics.
        BugSenseHandler.setup(this, BUGSENSE_API_KEY);
    }

    //Enable analytics session. Should be first (at least before any Flurry calls).
    if (!HIVAwarenessActivity.DEBUG)
        FlurryAgent.onStartSession(this, HIVAwarenessActivity.FLURRY_API_KEY);

    if (mBackupManagerAvailable) {
        mBackupManagerWrapper = new BackupManagerWrapper(this);//TODO: should this be app context?
        Log.i(TAG, "BackupManager API available.");
    } else {
        Log.i(TAG, "BackupManager API not available.");
    }

    //Load the default preferences values. Should be done first at every entry into the app.
    PreferenceManager.setDefaultValues(HIVAwarenessActivity.getAppCtxt(), PREFS, MODE_PRIVATE,
            R.xml.preferences, false);
    HIVAwarenessActivity.dataChanged();

    //Obtain a connection to the preferences.
    SharedPreferences prefs = getSharedPreferences(PREFS, MODE_PRIVATE);

    mGender = Gender.valueOf(prefs.getString(PREFS_GENDER, "male"));

    String region = prefs.getString(PREFS_REGION, null);
    if (region == null) {
        mRegion = null;
    }
    caught = prefs.getInt(PREFS_INFECTED, -1);

    if (caught == -1) {
        calculateInitial(mRegion == null);
    } else {

    }

    // Check for available NFC Adapter
    mNfcAdapter = NfcAdapter.getDefaultAdapter(HIVAwarenessActivity.getAppCtxt());
    if (mNfcAdapter == null) {
        Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
        if (!DEBUG)
            finish();
    }
    mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("application/net.lp.hivawareness.beam");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mIntentFiltersArray = new IntentFilter[] { ndef };
    mTechListsArray = new String[][] { new String[] { NfcF.class.getName() } };
}

From source file:org.bohrmeista.chan.ui.service.WatchNotifier.java

@SuppressWarnings("deprecation")
private Notification getNotificationFor(String tickerText, String title, String content, int count,
        List<CharSequence> lines, boolean makeSound, Pin targetPin) {

    Intent intent = new Intent(this, BoardActivity.class);
    intent.setAction(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_LAUNCHER);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP
            | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

    intent.putExtra("pin_id", targetPin == null ? -1 : targetPin.id);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentIntent(pendingIntent);

    if (tickerText != null) {
        tickerText = tickerText.substring(0, Math.min(tickerText.length(), 50));
    }//from ww w.  ja va2s .  c o  m

    builder.setTicker(tickerText);
    builder.setContentTitle(title);
    builder.setContentText(content);

    if (count >= 0) {
        builder.setContentInfo(Integer.toString(count));
        builder.setNumber(count);
    }

    builder.setSmallIcon(R.drawable.ic_stat_notify);

    Intent pauseWatching = new Intent(this, WatchNotifier.class);
    pauseWatching.putExtra("pause_pins", true);

    PendingIntent pauseWatchingPending = PendingIntent.getService(this, 0, pauseWatching,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder.addAction(R.drawable.ic_action_pause, getString(R.string.watch_pause_pins), pauseWatchingPending);

    if (makeSound) {
        builder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    }

    if (lines != null) {
        NotificationCompat.InboxStyle style = new NotificationCompat.InboxStyle();
        for (CharSequence line : lines.subList(Math.max(0, lines.size() - 10), lines.size())) {
            style.addLine(line);
        }
        style.setBigContentTitle(title);
        builder.setStyle(style);
    }

    return builder.getNotification();
}

From source file:com.veniosg.dir.android.util.Notifier.java

public static void showExtractDoneNotification(boolean success, int notId, File extractedTo, Context context) {
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);

    if (!shouldShowDoneNotification(notId, success)) {
        notificationManager.cancel(notId);
    } else {//from  w  w w  . j a  va 2  s  .  co m
        Intent browseIntent = new Intent(context, FileManagerActivity.class);
        browseIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        browseIntent.setData(Uri.fromFile(extractedTo));

        Notification not = new NotificationCompat.Builder(context, CHANNEL_FILEOPS).setAutoCancel(true)
                .setContentTitle(context
                        .getString(success ? R.string.notif_extracted_success : R.string.notif_extracted_fail))
                .setContentText(extractedTo.getName())
                .setContentIntent(getActivity(context, 0, browseIntent, FLAG_CANCEL_CURRENT)).setOngoing(false)
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setSmallIcon(R.drawable.ic_stat_notify_compress_5)
                .setTicker(context
                        .getString(success ? R.string.notif_extracted_success : R.string.notif_extracted_fail))
                .setOnlyAlertOnce(true).build();

        notificationManager.notify(notId, not);
    }
}

From source file:info.schnatterer.nusic.android.application.NusicApplication.java

/**
 * Writes an android notification that has the localized title of the app.
 * Overwrites any previous with the same <code>id</code>.
 * //from  w w w.  j  a  v a 2s  . c om
 * @param id
 *            An identifier for this notification unique within your
 *            application, can be used to change the notification later
 * @param text
 *            first line of text bellow the title
 * @param subtext
 *            second line of text bellow the title
 * @param smallIconId
 *            A resource ID in the application's package of the drawable to
 *            use.
 * @param largeIcon
 *            large icon that is shown in the ticker and notification.
 * @param cls
 *            activity to be launched on click
 * @param extras
 *            extended data to be passed to the activity
 */
public static void notify(Notification id, String text, String subtext, int smallIconId, Bitmap largeIcon,
        Class<? extends Context> cls, Bundle extras) {
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(getContext(), cls);
    /*
     * Make sure the intent is also delivered when the application is
     * already running in a task.
     * 
     * Note: On Android 2.x the intent is not delivered when another
     * activity of the same application is running. Instead the application
     * is only brought to foreground.
     */
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    if (extras != null) {
        resultIntent.putExtras(extras);
    }
    /*
     * The stack builder object will contain an artificial back stack for
     * the started Activity. This ensures that navigating backward from the
     * Activity leads out of your application to the home screen.
     */
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(cls);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    /*
     * Make sure to deliver the intent just created even though there
     * already is an intent with the same request ID.
     */
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(id.ordinal(),
            PendingIntent.FLAG_UPDATE_CURRENT);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getContext())
            .setSmallIcon(smallIconId).setLargeIcon(largeIcon).setContentIntent(resultPendingIntent)
            .setAutoCancel(true);
    if (subtext != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        /*
         * Subtext seems to be available starting with 4.1?! So we don't
         * show the app name in order to have more room for information. The
         * user still has the icon to identify the app.
         */

        notificationBuilder.setContentTitle(text).setContentText(subtext);
    } else {
        notificationBuilder.setContentTitle(getContext().getString(R.string.app_name)).setContentText(text)
                .setSubText(subtext);
    }
    NotificationManager notificationManager = (NotificationManager) getContext()
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // id allows you to update the notification later on.
    notificationManager.notify(id.ordinal(), notificationBuilder.build());
    Log.i(Constants.LOG, "Notifcation: " + text + subtext);
}

From source file:com.securekey.sdk.sample.ReadCardActivity.java

private void enableForegroundDispatch() {
    Log.i("SDKSample", "enable foreground dispatch");
    if (NfcAdapter.getDefaultAdapter(this) != null) {
        try {//from w  w w  . j a  v a 2 s .c  om
            NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this,
                    PendingIntent.getActivity(this, 0,
                            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0),
                    new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) }, new String[][] {
                            new String[] { NfcA.class.getName() }, new String[] { NfcB.class.getName() } });
        } catch (Exception e) {
            Log.i("SDKSample", "enableForegroundDispatch failed");
        }
    }
}

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  . j a  v  a2 s . 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.hardcopy.retrowatch.RssFragment.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn_delete:
        if (mCurrentRssObject == null || mCurrentRssObject.mId < 0)
            break;
        mFragmentListener.OnFragmentCallback(IFragmentListener.CALLBACK_REQUEST_DELETE_RSS, 0, 0, null, null,
                (Object) mCurrentRssObject);

        // Close soft keyboard
        InputMethodManager imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mEditUrl.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(mEditTitle.getWindowToken(), 0);
        break;/*w  w w .j  a v a  2  s  .  c  o  m*/

    case R.id.btn_add:
        if (mCurrentRssObject != null) {
            String url = mEditUrl.getText().toString();
            String title = mEditTitle.getText().toString();

            // Check input fields
            if (url == null || url.isEmpty() || title == null || title.isEmpty()) {
                Toast.makeText(mContext, mContext.getString(R.string.warning_type_rss_field),
                        Toast.LENGTH_SHORT).show();
            } else {
                mCurrentRssObject.mName = title;
                mCurrentRssObject.mURL = url;

                if (mButtonAdd.getText().equals(mContext.getString(R.string.command_add))) {
                    // Add RSS
                    mFragmentListener.OnFragmentCallback(IFragmentListener.CALLBACK_REQUEST_ADD_RSS, 0, 0, null,
                            null, mCurrentRssObject);
                    // makeDefaultRssObject();      // Make new RSS object and set data on widget
                } else {
                    // Edit RSS
                    mFragmentListener.OnFragmentCallback(IFragmentListener.CALLBACK_REQUEST_EDIT_RSS, 0, 0,
                            null, null, mCurrentRssObject);
                    // makeDefaultRssObject();      // Make new RSS object and set data on widget
                }
            }

            // Close soft keyboard
            InputMethodManager imm2 = (InputMethodManager) mContext
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm2.hideSoftInputFromWindow(mEditTitle.getWindowToken(), 0);
            imm2.hideSoftInputFromWindow(mEditUrl.getWindowToken(), 0);
        }
        break;

    case R.id.btn_new:
        makeDefaultRssObject(); // Make new RSS object and set data on widget

        // Close soft keyboard
        InputMethodManager imm3 = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm3.hideSoftInputFromWindow(mEditTitle.getWindowToken(), 0);
        imm3.hideSoftInputFromWindow(mEditUrl.getWindowToken(), 0);
        break;

    case R.id.btn_find_more:
        Intent i2 = new Intent(mContext, RetroWebViewActivity.class);
        i2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        i2.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        Uri u = Uri.parse(Constants.PROJECT_FEED_SEARCH_URL);
        i2.setData(u);
        startActivity(i2);
        break;

    } // End of switch()
}

From source file:com.playtech.ezpush.gcm.GcmIntentService.java

private void showNotification(Bundle extras) {

    Intent intent = new Intent(getApplicationContext(), MainActivity.class);

    NotificationManager notificationManager = (NotificationManager) this
            .getSystemService(this.NOTIFICATION_SERVICE);
    CharSequence message = extras.getString(EXTRA_MESSAGE);
    intent.putExtra(NOTIFICATION_MESSAGE, message);

    CharSequence title = extras.getString(EXTRA_HEADER);
    if (title == null)
        title = NOTIFICATION_TITLE;//from  ww  w  .  j  av a  2 s. c o m

    String aid = extras.getString("application_id");
    intent.putExtra("APP_ID", aid);

    String nid = extras.getString("nid");
    intent.putExtra("NOTIFICATION_ID", nid);
    intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    Notification.InboxStyle style = new Notification.InboxStyle();
    style.addLine(message);

    for (String s : extras.keySet()) {
        if (!containsKey(s)) {
            style.addLine(s + ":" + extras.getString(s));
        }
    }

    PendingIntent pendingIntent = PendingIntent.getActivity(this, intent.hashCode(), intent,
            PendingIntent.FLAG_ONE_SHOT);
    Notification.Builder nb = new Notification.Builder(this).setContentTitle(title).setContentText(message)
            .setSmallIcon(R.mipmap.ezpush_logo)
            .setLargeIcon(loadBitmap("http://ursynoteka.pl/wp-content/uploads/2012/04/message_new.png"))
            .setStyle(style).setContentIntent(pendingIntent).setAutoCancel(true);

    if (extras.containsKey(EXTRA_SOUND)) {
        nb.setSound(Uri.parse(extras.getString(EXTRA_SOUND)));
    }
    if (extras.containsKey(EXTRA_BANNER)) {
        Bitmap bitmap = loadBitmap(extras.getString(EXTRA_BANNER));
        if (bitmap != null) {
            NotificationCompat.BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
                    .setBigContentTitle(NOTIFICATION_TITLE).setSummaryText(message).bigPicture(bitmap);
        }
    }
    if (extras.containsKey(EXTRA_ICON)) {
        String iconUrl = extras.getString(EXTRA_ICON);
        Bitmap bitmap = loadBitmap(iconUrl);
        if (bitmap != null) {
            nb.setLargeIcon(bitmap);
        }
    }

    Notification notification = nb.build();

    notificationManager.notify(notification.hashCode(), notification);
}

From source file:nl.johndekroon.dma.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from www. j  a va2 s.  c  o m*/
private static void generateNotification(Context context, String message) {
    int icon = R.drawable.ic_stat_gcm;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MainActivity.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.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(0, notification);
}