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:ca.ualberta.cs.drivr.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    userManager.setConnectivityManager((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE));

    /**/*from w  ww.j  ava  2  s. c om*/
     * This calls the login activity a the beginning if there is no local user stored
     */
    if (userManager.getUser().getUsername().isEmpty()) {
        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    this.requestWindowFeature(Window.FEATURE_NO_TITLE);

    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    context = getApplicationContext();
    PreferenceManager.setDefaultValues(this, R.xml.pref_driver_mode, false);

    setSupportActionBar(toolbar);

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
    }

    mFragment = (SupportMapFragment) this.getSupportFragmentManager().findFragmentById(R.id.main_map);
    mFragment.getMapAsync(this);

    autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager()
            .findFragmentById(R.id.place_autocomplete_fragment);

    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
        @Override
        public void onPlaceSelected(Place place) {
            ConcretePlace concretePlace = new ConcretePlace(place);
            Gson gson = new GsonBuilder().registerTypeAdapter(Uri.class, new UriSerializer()).create();
            if (userManager.getUserMode().equals(UserMode.RIDER)) {
                Intent intent = new Intent(MainActivity.this, NewRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(NewRequestActivity.EXTRA_PLACE, concretePlaceJson);
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);

            } else if (userManager.getUserMode().equals(UserMode.DRIVER)) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                String concretePlaceJson = gson.toJson(concretePlace);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, concretePlaceJson);
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, "");
                Log.i(TAG, "Place: " + place.getName() + ", :" + place.getLatLng());
                startActivity(intent);
            }
        }

        @Override
        public void onError(Status status) {
            // Do nothing
        }
    });

    // Using the floating action button menu system
    final FloatingActionMenu fabMenu = (FloatingActionMenu) findViewById(R.id.main_fab_menu);
    FloatingActionButton fabSettings = (FloatingActionButton) findViewById(R.id.fabSettings);
    FloatingActionButton fabRequests = (FloatingActionButton) findViewById(R.id.main_fab_requests);
    FloatingActionButton fabProfile = (FloatingActionButton) findViewById(R.id.main_fab_profile);
    FloatingActionButton fabHistory = (FloatingActionButton) findViewById(R.id.main_fah_history);
    FloatingActionButton fabLogin = (FloatingActionButton) findViewById(R.id.main_fab_login);
    final FloatingActionButton fabDriver = (FloatingActionButton) findViewById(R.id.main_driver_mode);
    final FloatingActionButton fabRider = (FloatingActionButton) findViewById(R.id.main_rider_mode);

    // Hide the settings FAB
    fabSettings.setVisibility(View.GONE);

    /*
    Change between user and driver mode. Will probably be replaced with an option in settings.
    For now the visibility of this is set to gone because we should not have too many FABs.
    Having too many FABs may cause confusion and rendering issues on small screens.
    */
    keywordEditText = (EditText) findViewById(R.id.main_keyword_edit_text);
    FloatingActionButton fabMode = (FloatingActionButton) findViewById(R.id.main_fab_mode);
    fabMode.setVisibility(View.GONE);
    if (userManager.getUserMode().equals(UserMode.RIDER)) {
        fabRider.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.GONE);
    } else {
        fabDriver.setVisibility(View.GONE);
        keywordEditText.setVisibility(View.VISIBLE);
    }

    keywordEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                Intent intent = new Intent(MainActivity.this, SearchRequestActivity.class);
                intent.putExtra(SearchRequestActivity.EXTRA_PLACE, "");
                intent.putExtra(SearchRequestActivity.EXTRA_KEYWORD, keywordEditText.getText().toString());
                keywordEditText.setText("");
                keywordEditText.clearFocus();
                startActivity(intent);
            }
            return true;
        }
    });

    fabMode.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked mode fab");
            /*
            Will be able to implement code below once elasticSearch is up and running
            UserManager userManager = null; // Once elasticSearch is working will replace with finding a User
            if (userManager.getUserMode() == UserMode.DRIVER) {
            userManager.setUserMode(UserMode.RIDER);
            }
            else if (userManager.getUserMode() == UserMode.RIDER) {
            userManager.setUserMode(UserMode.DRIVER);
            //Will have to implement a method "FindNearbyRequests" to get requests whose source
            // is nearby and display it on the map
            //Intent intent = new Intent((MainActivity.this, FindNearbyRequests.class);)
            //startActivity(intent);
            }*/
        }
    });

    fabDriver.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (userManager.getUser().getVehicleDescription().isEmpty()) {
                /*
                * From: http://stackoverflow.com/a/29048271
                * Author: Syeda Zunairah
                * Accessed: November 29, 2016
                * Creates a dialog box with an edit text to get the vehicle description.
                */
                AlertDialog.Builder alert = new AlertDialog.Builder(v.getContext());
                final EditText edittext = new EditText(v.getContext());
                edittext.setText("Vechicle Make");
                edittext.clearComposingText();
                alert.setTitle("Become a Driver!");
                alert.setMessage(
                        "Drivers are require to enter vehicle information!\n\nPlease enter your vehicle's make");

                alert.setView(edittext);

                alert.setPositiveButton("Save Description", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        String vehicleDescription = edittext.getText().toString();
                        if (!vehicleDescription.isEmpty()) {
                            userManager.getUser().setVehicleDescription(vehicleDescription);
                            userManager.notifyObservers();
                            userManager.setUserMode(UserMode.DRIVER);
                            ElasticSearch elasticSearch = new ElasticSearch(
                                    userManager.getConnectivityManager());
                            elasticSearch.updateUser(userManager.getUser());
                            keywordEditText.setVisibility(View.VISIBLE);
                            fabDriver.setVisibility(View.GONE);
                            fabRider.setVisibility(View.VISIBLE);
                            fabMenu.close(true);
                        }
                        dialog.dismiss();
                    }
                });

                alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        dialog.dismiss();
                    }
                });

                AlertDialog newAlert = alert.create();
                newAlert.show();
            }
            if (!userManager.getUser().getVehicleDescription().isEmpty()) {
                userManager.setUserMode(UserMode.DRIVER);
                keywordEditText.setVisibility(View.VISIBLE);
                fabDriver.setVisibility(View.GONE);
                fabRider.setVisibility(View.VISIBLE);
                fabMenu.close(true);
            }
        }
    });

    fabRider.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            userManager.setUserMode(UserMode.RIDER);
            keywordEditText.setVisibility(View.GONE);
            fabRider.setVisibility(View.GONE);
            fabDriver.setVisibility(View.VISIBLE);
            fabMenu.close(true);
        }
    });

    fabLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabSettings.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked settings fab");
            Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked profile fab");
            Intent intent = new Intent(MainActivity.this, ProfileActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    fabHistory.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked history fab");
            Intent intent = new Intent(MainActivity.this, RequestHistoryActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });

    fabRequests.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Log.i(TAG, "clicked requests fab");
            Intent intent = new Intent(MainActivity.this, RequestsListActivity.class);
            fabMenu.close(true);
            startActivity(intent);
        }
    });
    setNotificationAlarm(context);
}

From source file:com.battlelancer.seriesguide.ui.BaseNavDrawerActivity.java

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    Intent launchIntent = null;/*from   w ww  .  ja  va 2 s.  c o m*/

    switch (position) {
    case MENU_ITEM_SHOWS_POSITION:
        if (this instanceof ShowsActivity) {
            break;
        }
        launchIntent = new Intent(this, ShowsActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Shows");
        break;
    case MENU_ITEM_LISTS_POSITION:
        if (this instanceof ListsActivity) {
            break;
        }
        launchIntent = new Intent(this, ListsActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Lists");
        break;
    case MENU_ITEM_MOVIES_POSITION:
        if (this instanceof MoviesActivity) {
            break;
        }
        launchIntent = new Intent(this, MoviesActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Movies");
        break;
    case MENU_ITEM_STATS_POSITION:
        if (this instanceof StatsActivity) {
            break;
        }
        launchIntent = new Intent(this, StatsActivity.class).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Statistics");
        break;
    case MENU_ITEM_SETTINGS_POSITION:
        launchIntent = new Intent(this, SeriesGuidePreferences.class);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Settings");
        break;
    case MENU_ITEM_HELP_POSITION:
        launchIntent = new Intent(this, HelpActivity.class);
        Utils.trackAction(this, TAG_NAV_DRAWER, "Help");
        break;
    case MENU_ITEM_SUBSCRIBE_POSITION:
        if (Utils.isAmazonVersion()) {
            launchIntent = new Intent(this, AmazonBillingActivity.class);
        } else {
            launchIntent = new Intent(this, BillingActivity.class);
        }
        Utils.trackAction(this, TAG_NAV_DRAWER, "Unlock");
        break;
    }

    // already displaying correct screen
    if (launchIntent != null) {
        final Intent finalLaunchIntent = launchIntent;
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                goToNavDrawerItem(finalLaunchIntent);
            }
        }, NAVDRAWER_CLOSE_DELAY);
    }

    mDrawerLayout.closeDrawer(Gravity.START);
}

From source file:ch.ethz.twimight.activities.TwimightBaseActivity.java

/**
 * Handle options menu selection//from w  w w.j  a v  a 2 s .  com
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    Intent i;
    switch (item.getItemId()) {

    case R.id.menu_write_tweet:
        startActivity(new Intent(getBaseContext(), NewTweetActivity.class));
        break;

    case R.id.menu_search:
        onSearchRequested();
        break;

    case android.R.id.home:
        // app icon in action bar clicked; go home
        i = new Intent(this, ShowTweetListActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(i);
        return true;

    case R.id.menu_my_profile:
        Uri uri = Uri
                .parse("content://" + TwitterUsers.TWITTERUSERS_AUTHORITY + "/" + TwitterUsers.TWITTERUSERS);
        Cursor c = getContentResolver().query(uri, null,
                TwitterUsers.COL_TWITTERUSER_ID + "=" + LoginActivity.getTwitterId(this), null, null);
        if (c.getCount() != 1)
            return false;
        c.moveToFirst();
        int rowId = c.getInt(c.getColumnIndex("_id"));

        if (rowId > 0) {
            // show the local user
            i = new Intent(this, ShowUserActivity.class);
            i.putExtra("rowId", rowId);
            startActivity(i);
        }
        c.close();
        break;

    case R.id.menu_messages:
        // Launch User Messages
        i = new Intent(this, ShowDMUsersListActivity.class);
        startActivity(i);
        break;

    case R.id.menu_settings:
        // Launch PrefsActivity
        i = new Intent(this, PrefsActivity.class);
        startActivity(i);
        break;

    case R.id.menu_logout:
        // In disaster mode we don't allow logging out
        if (PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
                .getBoolean("prefDisasterMode", Constants.DISASTER_DEFAULT_ON) == false) {
            showLogoutDialog();
        } else {
            Toast.makeText(this, R.string.disable_disastermode, Toast.LENGTH_LONG).show();
        }
        break;
    case R.id.menu_about:
        // Launch AboutActivity
        i = new Intent(this, AboutActivity.class);
        startActivity(i);
        break;

    default:
        return false;
    }
    return true;
}

From source file:com.wso2.mobile.mdm.services.PolicyTester.java

@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public PolicyTester(Context context, JSONArray recJArray, int type, String msgID) {
    this.context = context;
    devicePolicyManager = (DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);
    appList = new ApplicationManager(context);
    deviceInfo = new DeviceInfo(context);
    deviceState = new PhoneState(context);

    if (type == POLICY_MONITOR_TYPE_NO_ENFORCE_RETURN) {
        IS_ENFORCE = false;/*from ww  w.  j av a 2 s.  c  o m*/
    } else if (type == POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN) {
        IS_ENFORCE = false;
    } else if (type == POLICY_MONITOR_TYPE_ENFORCE_RETURN) {
        IS_ENFORCE = true;
    } else {
        IS_ENFORCE = false;
        type = POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN;
    }

    SharedPreferences mainPref = context.getSharedPreferences("com.mdm", Context.MODE_PRIVATE);
    policy = mainPref.getString("policy", "");

    try {
        JSONArray jArray = null;
        if (recJArray != null) {
            jArray = recJArray;
        } else {
            jArray = new JSONArray(policy);
        }
        Log.e("POLICY ARAY : ", jArray.toString());
        for (int i = 0; i < jArray.length(); i++) {
            JSONObject policyObj = (JSONObject) jArray.getJSONObject(i);
            if (policyObj.getString("data") != null && policyObj.getString("data") != "") {
                testPolicy(policyObj.getString("code"), policyObj.getString("data"));
            }
        }

        JSONObject rootObj = new JSONObject();
        try {
            if (deviceInfo.isRooted()) {
                rootObj.put("status", false);
            } else {
                rootObj.put("status", true);
            }
            rootObj.put("code", "notrooted");
            finalArray.put(rootObj);
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        Log.e("MONITOR POLICY : ", policy);
        Log.e("MONITOR USER MESSAGE : ", usermessage);
        //Display an alert to the user about policy violation
        if (policy != null && policy != "") {
            if (usermessage != null && usermessage != ""
                    && type == POLICY_MONITOR_TYPE_NO_ENFORCE_MESSAGE_RETURN) {
                Intent intent = new Intent(context, AlertActivity.class);
                intent.putExtra("message", usermessage);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
                        | Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(intent);
            }
        }

        returnJSON.put("code", CommonUtilities.OPERATION_POLICY_MONITOR);
        returnJSON.put("data", finalArray);

        Map<String, String> params = new HashMap<String, String>();
        params.put("code", CommonUtilities.OPERATION_POLICY_MONITOR);
        params.put("msgID", msgID);
        params.put("status", "200");
        params.put("data", finalArray.toString());

        ServerUtilities.pushData(params, context);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.carpool.dj.carpool.model.GcmIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *//*from w  ww . j  a va 2  s .  co m*/
@SuppressWarnings("deprecation")
private static void generateNotification(Context context, String message, Bundle data, String type) {

    int icon = R.drawable.ic_launcher;
    long when = System.currentTimeMillis();
    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    // Notification notification = new Notification(icon, message, when);
    Notification notification = new Notification.Builder(context)
            .setContentTitle(Utils.nowActivity.getString(R.string.app_name)).setContentText(message)
            .setSmallIcon(icon).setWhen(when).setSound(alarmSound).build();

    // String title = context.getString(R.string.app_name);

    Intent notificationIntent = null;
    if ("CarEvent".equals(type)) {
        notificationIntent = new Intent(context, ContentActivity.class);
    } else {
        return;
    }
    notificationIntent.putExtras(data);
    // 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,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, Utils.nowActivity.getString(R.string.app_name), message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    notificationManager.notify(0, notification);

}

From source file:com.automated.taxinow.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from  ww  w. ja va  2s.  c o m
private void generateNotification(Context context, String message) {
    // System.out.println("this is message " + message);
    // System.out.println("NOTIFICATION RECEIVED!!!!!!!!!!!!!!" + message);
    int icon = R.drawable.ic_launcher;
    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, MainDrawerActivity.class);
    notificationIntent.putExtra("fromNotification", "notification");
    // 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,
            PendingIntent.FLAG_UPDATE_CURRENT);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    System.out.println("notification====>" + message);
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    // notification.defaults |= Notification.DEFAULT_LIGHTS;
    notification.flags |= Notification.FLAG_SHOW_LIGHTS;
    notification.ledARGB = 0x00000000;
    notification.ledOnMS = 0;
    notification.ledOffMS = 0;
    notificationManager.notify(0, notification);
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wakeLock = pm.newWakeLock(
            PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE,
            "WakeLock");
    wakeLock.acquire();
    wakeLock.release();
}

From source file:org.transdroid.core.seedbox.XirvikSharedSettingsActivity.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@OptionsItem(android.R.id.home)
protected void navigateUp() {
    MainSettingsActivity_.intent(this).flags(Intent.FLAG_ACTIVITY_CLEAR_TOP).start();
}

From source file:com.andremion.heroes.ui.character.view.CharacterActivity.java

@Nullable
@Override/*w ww.  j  a va  2 s  .com*/
public Intent getParentActivityIntent() {
    //noinspection ConstantConditions
    return super.getParentActivityIntent().addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}

From source file:com.cbtec.eliademy.GCMIntentService.java

/**
 * Issues a notification to inform the user that server has sent a message.
 *///from w  w w  . j a v  a 2s  . c o  m

private static void generateNotification(Context context, String message) {
    int icon = R.drawable.icon;
    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, Eliademy.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);
}

From source file:chron.carlosrafael.chatapp.MyFirebaseMessagingService.java

/**
 * Create and show a simple notification containing the received FCM message.
 *
 * @param messageBody FCM message body received.
 *///w  w  w  . jav a 2s  .  co  m
private void sendNotification(String messageBody, String messageUser) {

    //Se ainda nao tiver clicado na notification a ID vai ter que ser a mesma
    //Se tiver clicado entao temos que gerar uma nova ID
    int notificationID;
    if (NotificationHandler.createNewNotification) {
        Random generator = new Random();
        notificationID = generator.nextInt(100);

        NotificationHandler.onGoingNotificationID = notificationID;

        //Dizendo que nao precisa criar uma nova notificacao ate o usuario clicar na notificacao e abrir o chat
        NotificationHandler.createNewNotification = false;
    } else {
        notificationID = NotificationHandler.onGoingNotificationID;
    }

    //Quando o usuario clicar ele vai pra o MainActivity
    Intent intent = new Intent(this, HomeActivity.class);

    //Botando um Extra para quando ele abrir por um Intent vindo do notification ele para de acumular as
    //mensagens de notificacao
    intent.putExtra("fromNotification", true);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher).setContentTitle("New message in chat")
            .setContentText(messageUser + " : " + messageBody).setAutoCancel(true).setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

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

    //Adicionando as mensagens no ArrayList que mantem todas as mensagens da notification que ainda vai ser vista
    NotificationHandler.notificationMessages.add(messageUser + " : " + messageBody);

    //Se nao eh pra criar uma nova notificacao entao temos que:
    // 1 - Adicionar essa mensagem como a ultima no ArrayList da notificacao
    // 2 - Ler o ArrayList pra criar o InboxStyle com todas as mensagens
    if (!NotificationHandler.createNewNotification) {

        int numMessages = NotificationHandler.notificationMessages.size();

        NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
        String title = (numMessages > 1) ? String.valueOf(numMessages) + " new messages in chat"
                : String.valueOf(numMessages) + " new message in chat";
        inboxStyle.setBigContentTitle(title);
        //inboxStyle.addLine(messageBody);
        for (int i = 0; i < NotificationHandler.notificationMessages.size(); i++) {
            //notificationBuilder.setContentText("Tamo no loop" + String.valueOf(i))
            notificationBuilder.setNumber(NotificationHandler.notificationMessages.size());
            inboxStyle.addLine(NotificationHandler.notificationMessages.get(i));
            //inboxStyle.addLine("Tamo no loop" + String.valueOf(i));
            // Because the ID remains unchanged, the existing notification is
            // updated.
            //            notificationManager.notify(
            //                    notificationID,
            //                    notificationBuilder.build());
        }

        notificationBuilder.setStyle(inboxStyle);
    }

    notificationManager.notify(notificationID, notificationBuilder.build());

    // Issue the notification here.

    //notificationManager.notify(notificationID /* ID of notification */, notificationBuilder.build());

}