Service and launching/re-launching Activity

2019-08-20 09:26发布

I am developing an app which runs has a basic UI and service which can receive emergencies'. If the user is in the UI and presses home or Back a notification appears and the service continues to run. If an emergency is received by the service I want to open the Activity into the UI. To do this I have to use startActivity in the service with the Intent flag FLAG_ACTIVITY_NEW_TASK.

But this means that, if the UI is still running in the background, it doesn't get re-opened. Many of my UI interactions from that point onward seem to happen on the old, hidden UI not the new UI which is open. Also If i close the current UI I sometimes have the old UI behind it.

I would like that from a service I can either bring the old ui to the front OR open a new one, depending whether or not the old UI is still running.

I have tried using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK together to both clear any other instances of the UI then open the UI in a new task but CLEAR_TASK is API 11 and over; my app supports 10.

Any help on the above is appreciated.

2条回答
够拽才男人
2楼-- · 2019-08-20 09:54

You can try to choose the launch mode "singleTask" in your manifest file :

<activity
    android:name=".MainActivity"
    android:launchMode="singleTask" >

With the "singleTask" launch mode, your activity will be instanciated only one time.

查看更多
你好瞎i
3楼-- · 2019-08-20 09:55

What I've done with this is do a bindService in the Activity's onResume (so you get the Service instance) and then add a method to the Service instance that receives a Handler instance from the Activity. In onPause you set the Handler on the Service to null. This way the Service knows (by checking its internal Handler instance) if there is already a UI available. If there is, it sends the Handler a Message that things happened. If there is no Handler, it launches a new UI.

查看更多
登录 后发表回答