Edy Baviloouk
Edy Baviloouk

Reputation: 33

Go to activity without starting it upon clicking on notification

Following the Android tutorial on Notification https://developer.android.com/guide/topics/ui/notifiers/notifications.html I'm able to display a Notification. What I do want, which is not explain in the article, is how to go to the activity without starting it. In fact I have an application with a couple of Activities. As soon as I enter one of those activities, a permanent Notification is shown which only disappears when the user leaves that activity. If the user then clicks on the Notification while my application is not on screen, I want the activity to be resumed without restarting it. The activity runs a counter. That's why it shouldn't be restarted.

Best regards

Upvotes: 0

Views: 1023

Answers (2)

Edy Baviloouk
Edy Baviloouk

Reputation: 33

This is how I manage to solve the problem. In the manifest.xml file set android:launchMode="singleTop" for that activity. And then you build the notification as follows:

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_directions_run_white_24dp).setContentTitle("My " + 
                    "notification").setContentText("Hello World!");
    // Creates an explicit intent for an Activity in your app
    Intent resultIntent = new Intent(context, PlayActivity.class);
    resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent resultPendingIntent = PendingIntent.getActivity(context, 0, resultIntent, 
            PendingIntent.FLAG_UPDATE_CURRENT);

    mBuilder.setContentIntent(resultPendingIntent);
    NotificationManager notificationManager = (NotificationManager) context.getSystemService
            (Context.NOTIFICATION_SERVICE);
    // mId allows you to update the notification later on.
    notificationManager.notify(NOTIFICATION_ID, mBuilder.build());

I haven't gone with using the SharedPreferences because the whole process of retrieving the counter value and restarting the activity could hold the counter for some time which may make lose its accuracy.

Upvotes: 2

Darish
Darish

Reputation: 11481

I want the activity to be resumed without restarting it. The activity runs a counter. That's why it shouldn't be restarted.

Well, you have to save the counter state during onPause() method and restore it during onResume() method.

How to save the state?

You can save the counter value into SharedPreferences. That will do the magic for you. cheers :)

Upvotes: 0

Related Questions