Android Implementation Click on the notification bar, first start the application and then open the target activity, the aurora push and other push can also refer to

Source: Internet
Author: User

I have integrated the Aurora push in the project, push the notification bar point open need to determine which interface to refer to this article, thank the author's selfless.

Situation Brief

In the process of developing an Android app, there is a need to launch a service in the app that runs in a standalone process, keeps a long connection to the server, displays the message that the server pushes over the notification bar, and sets the click action. Click to jump to the corresponding activity in the app. The problem is that the service is running as a standalone process, and after receiving the message and popping the notification, the app itself processes two things:

    1. App is running
    2. App has exited

For the first case, the processing is very simple, the parameters are passed directly into the intent and the corresponding activity can be opened.

However, the second case is complicated because the app has exited, and some of the actions in the activity that you want to open are dependent on the initialization of the app, which is done during the app startup process. For example, a shopping app pushes a message for a new item, and the user clicks on the notification to enter the activity for the product details, and the activity has an order button, which, when clicked, gets the user's ID from the local and a message to the server. Tell the server that a user ordered the item. These user information is obtained after a series of interactions with the server when the app is launched. If the app exits directly into the details activity and clicks on the purchase, it will fail because the user information is not available.

So at present to solve the problem, set the click Action in notification, if the app itself is running, jump directly to the target activity, if the app has exited, start the app to complete initialization, and then jump to the target activity.

Solutions and ideas

We assume that there are currently three activity:

    1. Splashactivity is used to display the app large image, while the user login and other operations, the server returned to the data to mainactivity.
    2. The main activity of the Mainactivity app.
    3. Detailactivity mainactivity Click button to enter activity to display the item details.

The service that pops up the notification is in another process.

What we want to achieve is to:

    1. Click the notification bar notification, if the app is running, then jump directly to detailactivity display specific content, in Detailactivity press the back key to return mainactivity
    2. Click the notification bar notification, if the app has exited, first from splashactivity to enter, display the app launch interface, the initialization of the operation to enter the mainactivity and then jump to detailactivity display specific content, Press the back key in Detailactivity to return to Mainactivity.

The initial idea is to determine whether the app process exists, if it exists, use startactivities to start mainactivity and detailactivity. Why do I have to start mainactivity instead of just starting detailactivity? Because of the following situation, all the activity in the process has exited, but the process has not been reclaimed by the system, when the process is determined to return true, and then only start detailactivity, press the back key task stack directly to the end, to return to the desktop. And the effect we want is to press the back key to return to the previous activity, which is mainactivity.

If the app process has exited and does not exist, start the app with a intent, which contains a bundle with the parameters required to start detailactivity in the bundle, which intent passed in Splashactivity, Again by the splashactivity to Mainactivity, in the mainactivity to add judgment, if there is this parameter, it means that the application is started from the notification bar, to jump to the detailactivity operation, otherwise is the general start.

Code implementation

With the approximate implementation of the idea, we have a demo of the actual operation.
First of all, our demo has a simple component:

    1. Pushservice, the service started in the new process, is responsible for listening to the server, receiving information from the server after the message broadcast, in this demo, in order to simplify, simply broadcast a message
    2. Shownotificationreceiver, Broadcastreceiver registered in the new process, after receiving the Pushservice message, will pop up the notification in the notification bar
    3. Notificationreceiver, the broadcastreceiver that is registered in the new process, is used to set the action of clicking Notifications in the notification bar to open an activity in the app
    4. Splashactivity, App launch page, first boot image, 3s enter mainactivity
    5. Mainactivity,app's main activity
    6. Activity that shows details in Detailactivity,app
Pushservice.java

The first is Pushservice, to start in a new process, add the following code to register the service in Androidmanifest.xml

<android:name= ". Pushservice "                 android:process=":p ush "/>

Pushservice's work is very simple, after launching a broadcast in the notification bar display notification, and then resident in the background

 Public classPushserviceextendsservice{@Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidonCreate () {Super. OnCreate (); LOG.I ("Pushservice", "Pushservice onCreate"); //send broadcasts with Alarmmanager timingAlarmmanager am =(Alarmmanager) Getsystemservice (Context.alarm_service); Intent Intent=NewIntent ( This, Shownotificationreceiver.class); Pendingintent pendingintent=Pendingintent.getbroadcast ( This, 0, intent, pendingintent.flag_update_current);    Am.set (Alarmmanager.elapsed_realtime, Systemclock.currentthreadtimemillis (), pendingintent); }}

Shownotificationreceiver.java

This broadcast class is used to pop up notifications in the notification bar

 Public classShownotificationreceiverextendsbroadcastreceiver{Private Static FinalString TAG = "Repeatreceiver"; @Override Public voidOnReceive (Context context, Intent Intent) {log.d (TAG,"Shownotificationreceiver OnReceive"); //set the action of clicking on the notification bar to start another broadcastIntent broadcastintent =NewIntent (context, notificationreceiver.class); Pendingintent pendingintent=pendingintent. Getbroadcast (Context,0, Broadcastintent, pendingintent.flag_update_current); Notificationcompat.builder Builder=NewNotificationcompat.builder (context); Builder.setcontenttitle ("This is the head of the notice."). Setticker ("This is the ticker of the notice."). Setcontentintent (pendingintent). Setsmallicon (Android.        r.drawable.ic_lock_idle_charging); LOG.I ("Repeat", "shownotification"); Notificationmanager Manager=(Notificationmanager) Context.getsystemservice (Context.notification_service); Manager.notify (2, Builder.build ()); }}

Notificationreceiver.java

Click on the notification bar, will send a broadcast, Notificationreceiver received the broadcast, will determine whether the app process is still alive, according to the different status of the app process, define different app launch mode

 Public classNotificationreceiverextendsbroadcastreceiver{@Override Public voidOnReceive (Context context, Intent Intent) {//determine if the app process is alive        if(Systemutils.isappalive (Context, "Com.liangzili.notificationlaunch")){            //If you survive, start detailactivity directly, but consider a situation where the app's process is still//but the task stack is empty, for example, the user clicks the Back button to exit the app, but the process has not been reclaimed by the system, if it is started directly//detailactivity, press the back key again to not return to mainactivity. So at the start//before detailactivity, start mainactivity first. LOG.I ("Notificationreceiver", "the app process is alive"); Intent mainintent=NewIntent (context, mainactivity.class); //set the Launchmode of the mainativity to Singletask, or add intent.flag_clear_top to the FLAG below,//If there is an instance of mainactivity in the task stack, it is moved to the top of the stack and the activity above it is cleared out of the stack.//If the mainactivity instance does not exist on the task stack, it is created at the top of the stackmainintent.setflags (Intent.flag_activity_new_task); Intent detailintent=NewIntent (context, detailactivity.class); Detailintent.putextra ("Name", "Rice cooker"); Detailintent.putextra ("Price", "58 yuan"); Detailintent.putextra ("Detail", "This is a good pot, this is the app process exists, directly start the activity"); Intent[] Intents={mainintent, detailintent};        Context.startactivities (intents); }Else {            //If the app process has been killed, restart the app and pass the detailactivity's startup parameters into the intent, with the parameters//splashactivity incoming mainactivity, this time the app initialization is complete, in mainactivity can be based on the incoming//parameter jumps to the detailactivity.LOG.I ("Notificationreceiver", "The app process is dead"); Intent launchintent=Context.getpackagemanager (). Getlaunchintentforpackage ("Com.liangzili.notificationlaunch"); Launchintent.setflags (Intent.flag_activity_new_task|intent.flag_activity_reset_task_if_needed); Bundle args=NewBundle (); Args.putstring ("Name", "Rice cooker"); Args.putstring ("Price", "58 yuan"); Args.putstring ("Detail", "This is a good pot, this is the app process does not exist, first start the application and then start the activity");            Launchintent.putextra (Constants.extra_bundle, args);        Context.startactivity (launchintent); }    }}

Splashactivity.java

Splashactivity.java first the app to start the picture, 3s into the mainactivity, if the start splashactivity intent with parameters, will be taken out of the parameters, into the mainactivity of the start intent

 Public classSplashactivityextendsappcompatactivity{@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_splash); //Hide ActionbarGetsupportactionbar (). Hide (); //enter mainactivity after 3 seconds countdown with handler        NewHandler (). postdelayed (NewRunnable () {@Override Public voidrun () {Intent Intent=NewIntent (splashactivity. This, Mainactivity.class); //If you start the app with an extra parameter in the intent, the app is launched from the action of clicking the notification bar//take the parameter out and pass it to the mainactivity                if(Getintent (). Getbundleextra (constants.extra_bundle)! =NULL) {Intent.putextra (Constants.extra_bundle, Getintent (). Getbundleextra (Co Nstants.                Extra_bundle));                } startactivity (Intent);            Finish (); }        }, 3000); }}

Mainactivity.java

Mainactivity, if there are parameters passed in, after the initialization, starting detailactivity according to the parameters, if there are no parameters passed in, this ends their own task

 Public classMainactivityextendsappcompatactivity {Private Static FinalString TAG = "Mainactivity"; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_main); Intent Intent=NewIntent ( This, Pushservice.class);        StartService (Intent); Settitle ("Mainactivity"); Bundle Bundle=getintent (). Getbundleextra (Constants.extra_bundle); if(Bundle! =NULL){            //if the bundle exists, take out the parameters and start the detailactivityString name = bundle.getstring ("name"); String Price= bundle.getstring ("Price"); String Detail= bundle.getstring ("detail"); Systemutils.startdetailactivity ( This, name, price, detail); LOG.I (TAG,"Launchparam exists, redirect to Detailactivity"); }} @Overrideprotected voidOnresume () {Super. Onresume (); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.menu_main, menu); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {//Handle Action Bar item clicks here. The Action Bar would//automatically handle clicks on the Home/up button, so long//As you specify a the parent activity in Androidmanifest.xml.        intID =Item.getitemid (); //noinspection simplifiableifstatement        if(id = =r.id.action_settings) {            return true; }        return Super. onoptionsitemselected (item); }}

Detailactivity.java

Simple, show incoming parameters:-D

 Public classDetailactivityextendsappcompatactivity{@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);        Setcontentview (R.layout.activity_detail); Getsupportactionbar (). Settitle ("Detailactivity"); String name= Getintent (). Getstringextra ("name"); String Price= Getintent (). Getstringextra ("Price")); String Detail= Getintent (). Getstringextra ("detail");        ((TextView) Findviewbyid (R.id.name)). SetText (name);        ((TextView) Findviewbyid (R.id.price)). SetText (price);    ((TextView) Findviewbyid (R.id.detail)). SetText (detail); }}

Turn from: Android implementation click the Notification bar, start the app before you open the target activity

Android Implementation Click on the notification bar, the first to start the application and then open the target activity, Aurora push and other push can also refer to (turn)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.