Show notification only if activity is not displayed

I have a background task that I would like to handle. The fact is that when the task is completed, I would like to trigger a new action to show the result to the user only if my main activity is displayed, otherwise I would like to send only a notification so that the user can see that the action is completed and can open it when wants to.

I thought to use the service to process the beginning and completion of the background task and broadcast the message when it ends, but in this case I have no way to find out if the activity was shown or the broadcast was not processed and I must send a notification.

So, this is my problem, and since my knowledge and experience in background tasks and services are limited, I decided to ask for help.

Thank you in advance for reading my case, I hope for help!

+6
source share
4 answers

Here is a good article that describes how to implement what you want: Activity or notification using ordered broadcasting .

The basic idea is to use ordered broadcasts. You must create a BroadcastReceiver that will live without any action. To do this, you must declare it in the AndroidManifest.xml file. This receiver will display Notification . You must also register another BroadcastReceiver with a higher priority in your main action, which will display something on the screen. Then you just need to send an ordered stream.

+23
source

Try it.

 private static boolean isInForeground; onResume(){ isInForground = true; } onPause(){ isInForground = false; } 

if isInForground is true , then the Activity is in Forground (Showing), otherwise it is not displayed.

if you want to know from anywhere, add the following to MainActivity.

 SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); onResume(){ pref = PreferenceManager.getDefaultSharedPreferences(this); prefEditor = prefs.edit(); prefEditor.putBoolean("isInForeground",true); prefEditor.commit(); } onPause(){ pref = PreferenceManager.getDefaultSharedPreferences(this); prefEditor = prefs.edit(); prefEditor.putBoolean("isInForeground", false); prefEditor.commit(); } 

Then from your service.

 pref = PreferenceManager.getDefaultSharedPreferences(this); if(pref.getBoolean("isInForeground", false)){ //MainActivity is in forground } else{ //not in forground } 
+2
source

It looks like you want to implement a task in a thread from a Service. You can have a constant static boolean value in the Activity that indicates whether the action is displayed. The activity is visible to the user in onResume() and is not displayed whenever onPause() called. Set boolean to true in onResume() and false in onPause() .

+1
source

you can use SharedPreferences; refresh activity preferences when it's onStart () or onStop (), and just check it in your service.

I hope that I will help.

0
source

Source: https://habr.com/ru/post/895873/


All Articles