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.example.mynsocial.BluetoothChat.java

public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    Log.i(TAG, "---------------------------------------");
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent,
            0);//  ww  w .  j  a va  2 s .com
    String[][] techList = new String[][] {};
    adapter.enableForegroundDispatch(activity, pendingIntent, null, techList);
}

From source file:de.qspool.clementineremote.ui.fragments.DownloadsFragment.java

private void playFile(Uri file) {
    Intent mediaIntent = new Intent();
    mediaIntent.setAction(Intent.ACTION_VIEW);
    mediaIntent.setDataAndType(file, "audio/*");
    mediaIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    if (mediaIntent.resolveActivity(getActivity().getPackageManager()) != null) {
        startActivity(mediaIntent);/*from   w w w  . ja  v a2s.  com*/
    } else {
        Toast.makeText(getActivity(), R.string.app_not_available, Toast.LENGTH_LONG).show();
    }
}

From source file:com.preguardia.app.notification.MyGcmListenerService.java

private void showMedicNotification(String title, String message, String consultationId) {
    // Prepare intent which is triggered if the notification is selected
    Intent intent = new Intent(this, ApproveConsultationActivity.class);

    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    intent.putExtra(Constants.EXTRA_CONSULTATION_ID, consultationId);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, Constants.MEDIC_REQUEST_CODE, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_stat_logo).setContentTitle(title).setContentText(message)
            .setAutoCancel(true).setSound(defaultSoundUri).setContentIntent(pendingIntent);

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

    notificationManager.notify(2, notificationBuilder.build());
}

From source file:com.chilliworks.chillisource.googleplay.core.GCMService.java

private void generateNotification(Context context, HashMap<String, String> inParams) {
    //if the application is active then pass this information on to the application.
    if (CSApplication.get() != null && CSApplication.get().isActive() == true) {
        //build the array of keys and values
        int dwNumEntries = inParams.size();
        String[] astrKeys = new String[dwNumEntries];
        String[] astrValues = new String[dwNumEntries];
        int dwCount = 0;
        for (String strKey : inParams.keySet()) {
            astrKeys[dwCount] = strKey;/*from  w w  w .  ja  v  a 2s . c om*/
            astrValues[dwCount] = inParams.get(strKey);
            dwCount++;
        }

        // Send this to the native side of the engine.
        mNativeInterface.OnRemoteNotificationReceived(astrKeys, astrValues);
    }
    // Otherwise display a notification.
    else {
        String strTitle = context.getString(ResourceHelper.GetDynamicResourceIDForField(context,
                ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_STRING, "app_name"));
        String strMessage = inParams.get("message");

        Intent notificationIntent = new Intent(context, CSActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

        Bitmap largeIconBitmap = null;
        int largeIconID = ResourceHelper.GetDynamicResourceIDForField(context,
                ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify_large");

        //If no large icon then use the small icon
        if (largeIconID == 0) {
            largeIconID = ResourceHelper.GetDynamicResourceIDForField(context,
                    ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify");
        }

        if (largeIconID > 0) {
            largeIconBitmap = BitmapFactory.decodeResource(context.getResources(), largeIconID);
        }

        Notification notification = new NotificationCompat.Builder(context).setContentTitle(strTitle)
                .setContentText(strMessage)
                .setSmallIcon(ResourceHelper.GetDynamicResourceIDForField(context,
                        ResourceHelper.RESOURCE_SUBCLASS.RESOURCE_DRAWABLE, "ic_stat_notify"))
                .setLargeIcon(largeIconBitmap).setContentIntent(intent).build();

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, notification);
    }
}

From source file:com.sftoolworks.nfcoptions.SelectActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);

    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    pendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    Intent intent = getIntent();//from   w  ww  . ja v  a 2s  .  c  o  m
    Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

    String title = getString(R.string.default_select_title);

    TextView textViewBottom = (TextView) findViewById(R.id.textView2);
    textViewBottom.setText("");

    if (rawMessages != null) {

        ArrayList<Object> entries = new ArrayList<Object>();

        String data = null;

        for (Parcelable rawMessage : rawMessages) {
            NdefMessage message = (NdefMessage) rawMessage;
            NdefRecord[] records = message.getRecords();
            if (records.length > 1) {
                byte[] bArray = records[1].getPayload();
                byte languageLength = bArray[0];

                languageLength++; // because of the length byte

                data = new String(bArray, languageLength, bArray.length - languageLength);
            }
        }

        try {
            JSONObject json = (JSONObject) new JSONTokener(data).nextValue();
            if (json.has("title"))
                title = json.getString("title");
            if (json.has("key"))
                selectKey = json.getString("key");
            if (json.has("options")) {
                JSONArray arr = json.getJSONArray("options");
                for (int i = 0; i < arr.length(); i++) {
                    entries.add(parseJObject(arr.getJSONObject(i)));
                }
            }

            ListView list = (ListView) findViewById(R.id.listView1);
            list.setAdapter(new OptionListAdapter(this, entries.toArray()));

            list.setOnItemClickListener(new ListView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int index, long id) {
                    CheckBox cb = (CheckBox) view.findViewById(R.id.optionListCheckBox);
                    cb.setChecked(!cb.isChecked());
                }
            });

            textViewBottom.setText(getString(R.string.tap_again));

        } catch (Exception e) {
            String message = getString(R.string.json_err);
            message += "\n";
            message += e.getMessage();

            Toast.makeText(this, message, Toast.LENGTH_LONG).show();

            Log.d(TAG, getString(R.string.json_err));
            Log.d(TAG, e.toString());
            Log.d(TAG, data);
        }
    } else {
        title = getString(R.string.no_tag);
    }

    TextView msg = (TextView) findViewById(R.id.textView1);
    msg.setText(title);

}

From source file:jahirfiquitiva.iconshowcase.services.NotificationsService.java

@SuppressWarnings("ResourceAsColor")
private void pushNotification(String content, int type, int ID) {

    Preferences mPrefs = new Preferences(this);

    String appName = Utils.getStringFromResources(this, R.string.app_name);

    String title = appName, notifContent = null;

    switch (type) {
    case 1://from  w w w. java2s.c  om
        title = getResources().getString(R.string.new_walls_notif_title, appName);
        notifContent = getResources().getString(R.string.new_walls_notif_content, content);
        break;
    case 2:
        title = appName + " " + getResources().getString(R.string.news).toLowerCase();
        notifContent = content;
        break;
    }

    // Send Notification
    NotificationManager notifManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this);
    notifBuilder.setAutoCancel(true);
    notifBuilder.setContentTitle(title);
    if (notifContent != null) {
        notifBuilder.setStyle(new NotificationCompat.BigTextStyle().bigText(notifContent));
        notifBuilder.setContentText(notifContent);
    }
    notifBuilder.setTicker(title);
    Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    notifBuilder.setSound(ringtoneUri);

    if (mPrefs.getNotifsVibrationEnabled()) {
        notifBuilder.setVibrate(new long[] { 500, 500 });
    } else {
        notifBuilder.setVibrate(null);
    }

    int ledColor = ThemeUtils.darkTheme ? ContextCompat.getColor(this, R.color.dark_theme_accent)
            : ContextCompat.getColor(this, R.color.light_theme_accent);

    notifBuilder.setColor(ledColor);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        notifBuilder.setPriority(Notification.PRIORITY_HIGH);
    }

    Class appLauncherActivity = getLauncherClass(getApplicationContext());

    if (appLauncherActivity != null) {
        Intent appIntent = new Intent(this, appLauncherActivity);
        appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP
                | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        appIntent.putExtra("notifType", type);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(appLauncherActivity);

        // Adds the Intent that starts the Activity to the top of the stack
        stackBuilder.addNextIntent(appIntent);
        PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
        notifBuilder.setContentIntent(resultPendingIntent);
    }

    notifBuilder.setOngoing(false);

    notifBuilder.setSmallIcon(R.drawable.ic_notifications);

    Notification notif = notifBuilder.build();

    if (mPrefs.getNotifsLedEnabled()) {
        notif.ledARGB = ledColor;
    }

    notifManager.notify(ID, notif);
}

From source file:com.jaguarlandrover.auto.remote.vehicleentry.RviService.java

static void sendNotification(Context ctx, String action, String... extras) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
    NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
    boolean fire = prefs.getBoolean("pref_fire_notifications", true);

    if (!fire)/*w ww .j av  a2  s.com*/
        return;

    NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx).setSmallIcon(R.drawable.rvi_not)
            .setAutoCancel(true).setContentTitle(ctx.getResources().getString(R.string.app_name))
            .setContentText(action);

    Intent targetIntent = new Intent(ctx, LockActivity.class);
    int j = 0;
    for (String ex : extras) {
        targetIntent.putExtra("_extra" + (++j), ex);
        targetIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    }
    PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, targetIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    nm.notify(0, builder.build());
}

From source file:com.meetingcpp.sched.gcm.command.NotificationCommand.java

private void processCommand(Context context, NotificationCommandModel command) {
    // Check format
    if (!"1.0.00".equals(command.format)) {
        LOGW(TAG, "GCM notification command has unrecognized format: " + command.format);
        return;/*from   ww w.j  a v a2s.  c o  m*/
    }

    // Check app version
    if (!TextUtils.isEmpty(command.minVersion) || !TextUtils.isEmpty(command.maxVersion)) {
        LOGD(TAG, "Command has version range.");
        int minVersion = 0;
        int maxVersion = Integer.MAX_VALUE;
        try {
            if (!TextUtils.isEmpty(command.minVersion)) {
                minVersion = Integer.parseInt(command.minVersion);
            }
            if (!TextUtils.isEmpty(command.maxVersion)) {
                maxVersion = Integer.parseInt(command.maxVersion);
            }
            LOGD(TAG, "Version range: " + minVersion + " - " + maxVersion);
            PackageInfo pinfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            LOGD(TAG, "My version code: " + pinfo.versionCode);
            if (pinfo.versionCode < minVersion) {
                LOGD(TAG, "Skipping command because our version is too old, " + pinfo.versionCode + " < "
                        + minVersion);
                return;
            }
            if (pinfo.versionCode > maxVersion) {
                LOGD(TAG, "Skipping command because our version is too new, " + pinfo.versionCode + " > "
                        + maxVersion);
                return;
            }
        } catch (NumberFormatException ex) {
            LOGE(TAG,
                    "Version spec badly formatted: min=" + command.minVersion + ", max=" + command.maxVersion);
            return;
        } catch (Exception ex) {
            LOGE(TAG, "Unexpected problem doing version check.", ex);
            return;
        }
    }

    // Check if we are the right audience
    LOGD(TAG, "Checking audience: " + command.audience);
    if ("remote".equals(command.audience)) {
        if (SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is remote and attendee is on-site");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is remote).");
        }
    } else if ("local".equals(command.audience)) {
        if (!SettingsUtils.isAttendeeAtVenue(context)) {
            LOGD(TAG, "Ignoring notification because audience is on-site and attendee is remote.");
            return;
        } else {
            LOGD(TAG, "Relevant (attendee is local).");
        }
    } else if ("all".equals(command.audience)) {
        LOGD(TAG, "Relevant (audience is 'all').");
    } else {
        LOGE(TAG, "Invalid audience on GCM notification command: " + command.audience);
        return;
    }

    // Check if it expired
    Date expiry = command.expiry == null ? null : TimeUtils.parseTimestamp(command.expiry);
    if (expiry == null) {
        LOGW(TAG, "Failed to parse expiry field of GCM notification command: " + command.expiry);
        return;
    } else if (expiry.getTime() < UIUtils.getCurrentTime(context)) {
        LOGW(TAG, "Got expired GCM notification command. Expiry: " + expiry.toString());
        return;
    } else {
        LOGD(TAG, "Message is still valid (expiry is in the future: " + expiry.toString() + ")");
    }

    // decide the intent that will be fired when the user clicks the notification
    Intent intent;
    if (TextUtils.isEmpty(command.dialogText)) {
        // notification leads directly to the URL, no dialog
        if (TextUtils.isEmpty(command.url)) {
            intent = new Intent(context, MyScheduleActivity.class)
                    .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else {
            intent = new Intent(Intent.ACTION_VIEW, Uri.parse(command.url));
        }
    } else {
        // use a dialog
        intent = new Intent(context, MyScheduleActivity.class).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_TITLE,
                command.dialogTitle == null ? "" : command.dialogTitle);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_MESSAGE,
                command.dialogText == null ? "" : command.dialogText);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_YES,
                command.dialogYes == null ? "OK" : command.dialogYes);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_NO, command.dialogNo == null ? "" : command.dialogNo);
        intent.putExtra(MyScheduleActivity.EXTRA_DIALOG_URL, command.url == null ? "" : command.url);
    }

    final String title = TextUtils.isEmpty(command.title) ? context.getString(R.string.app_name)
            : command.title;
    final String message = TextUtils.isEmpty(command.message) ? "" : command.message;

    // fire the notification
    ((NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE)).notify(0,
            new NotificationCompat.Builder(context).setWhen(System.currentTimeMillis())
                    .setSmallIcon(R.drawable.ic_stat_notification).setTicker(command.message)
                    .setContentTitle(title).setContentText(message)
                    //.setColor(context.getResources().getColor(R.color.theme_primary))
                    // Note: setColor() is available in the support lib v21+.
                    // We commented it out because we want the source to compile
                    // against support lib v20. If you are using support lib
                    // v21 or above on Android L, uncomment this line.
                    .setContentIntent(
                            PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT))
                    .setAutoCancel(true).build());
}

From source file:info.curtbinder.reefangel.phone.StatusActivity.java

/** Called when the activity is first created. */

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.status);/*from w  w  w.  j  a  v  a2  s.  c o m*/

    // Message Receiver stuff
    receiver = new StatusReceiver();
    filter = new IntentFilter(MessageCommands.UPDATE_DISPLAY_DATA_INTENT);
    filter.addAction(MessageCommands.UPDATE_STATUS_INTENT);
    filter.addAction(MessageCommands.ERROR_MESSAGE_INTENT);
    filter.addAction(MessageCommands.VORTECH_POPUP_INTENT);
    filter.addAction(MessageCommands.MEMORY_RESPONSE_INTENT);
    filter.addAction(MessageCommands.COMMAND_RESPONSE_INTENT);
    filter.addAction(MessageCommands.VERSION_RESPONSE_INTENT);
    filter.addAction(MessageCommands.OVERRIDE_RESPONSE_INTENT);
    filter.addAction(MessageCommands.OVERRIDE_POPUP_INTENT);
    filter.addAction(MessageCommands.CALIBRATE_RESPONSE_INTENT);

    vortechModes = getResources().getStringArray(R.array.vortechModeLabels);

    createViews();
    findViews();

    // update actionbar
    final ActionBar ab = getSupportActionBar();
    ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
    ab.setDisplayShowTitleEnabled(false);

    // set the max number of pages that we can have
    appPages = new View[POS_END];
    updatePageOrder();
    setPagerPrefs();

    // Check if this is the first run, if so we need to prompt the user
    // to configure before we start the service and proceed
    // this should be the last thing done in OnCreate()
    if (rapp.isFirstRun()) {
        Log.w(TAG, "First Run of app");
        Intent i = new Intent(this, FirstRunActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(i);
        finish();
    }

    // Scroll to controller page
    pager.setCurrentItem(POS_CONTROLLER);
}

From source file:com.jaspersoft.android.jaspermobile.activities.save.SaveReportService.java

private PendingIntent getSavedItemIntent() {
    Intent notificationIntent = NavigationActivity_.intent(this).currentSelection(R.id.vg_saved_items).get();

    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    return PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}