Android: test from a service, if an Activity is running. - android

I have a service that runs in background. I I wish it could perform an action, only if a certain activity is running. How can I test, from a service, if the activity is running?

You can use the Package Manager and the Activity Manager:
PackageManager: Class for retrieving various kinds of information related to the application packages that are currently installed on the device. You can find this class through getPackageManager().
ActivityManager: Interact with the overall activities running in the system.
But, a more simple approach would be: When starting your Activity (onCreate/onResume), send a message with service.send(..) or an Intent with service.onStartCommand(..) so the service knows that your particular Activity has been started.

Maybe you can do it the other way around, sending intent from your activity to the service.
For example, you can send an intent on the activity onResume, telling your service the activity is live, and another on onPause, telling the service the activity has stopped

Use the below method with your package name.It will return true if any of your activity is in foreground.
public boolean isForeground(String myPackage){
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > runningTaskInfo = am.getRunningTasks(1);
ComponentName componentInfo = runningTaskInfo.get(0).topActivity;
if(componentInfo.getPackageName().equals(myPackage)) return true;
return false;
}

Related

Add background music through out app

I'm having trouble adding background music to my app. I have three activities and I would like the music to keep playing regardless of whether the user switches activities or not. I am currently using a service to play the music but this results in the music starting and stopping every time a different activity starts.
I have found this solution several times throughout forums but it doesn't seem work:
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
player.stop();
}
}
You're supposed to add it to every activities onPause, and I did that and it still didn't work. The music doesn't stop when you switch between activities, but it also doesn't stop when you exit the app.
Thanks in advance for the help.
How is the service setup? Are you binding the service to an activity or are you passing an intent to the service. If the service is bound to an activity, that would explain why when you navigate to a different activity, that the service dies. The activity that the service is bound to is no longer there.
If you are running and passing an intent to the service, then hopefully, you aren't passing anything to the service to stop playback. If you navigate outside the app, the service should still be running in the foreground with a notification on your notification bar.
http://developer.android.com/guide/topics/media/mediaplayer.html
You might want to take a look at the guide I linked above.

Close the service from the library only when the entire app goes to the background

I searched a lot in the net about it, the solutions are based on onPause and onDestroy. I want to give a library to a developer who just needs to paste a few lines of code from the library in his app which will enable the developer to create a service and destroy it when his entire app is in the background.
Does the Android OS send some kind of signals or intents when the app or the activity is changed (other than onPause or onStop method), so that i can catch that in a broadcast receiver from my library and do some actions.
If you know the package name of your app, try this (put this following snippet in the onCreate method of your app):
ActivityManager am= (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
Then,
boolean exit = false;
while(!exit)
{
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
if(!componentInfo.getPackageName().equals("Your package name"))
{
//Do your work here
exit = true;
}
}
When you start your app, this will be put into componentInfo. The taskInfo.get(0).topActivity will return the activity in the foreground. Hence you can know that your app has gone to the background by comparing package using the second code snippet.
Note:Put this second code snippet in an Asynctask so that the checking of whether the app has started can be done in the background.

How to detect the state of an app other than mine?

I have looked around, but all suggestions are for checking state of my own app/activity.
using the Life Cycle.
I need to check if another app is in foreground/ running in background / paused .
Is it possible. Based on the state of the app i need to change my further actions.
ActivityManager acm=(ActivityManager) getSystemService(ACTIVITY_SERVICE);
List< ActivityManager.RunningTaskInfo > taskInfo = acm.getRunningTasks(1);
taskInfo.get(0).topActivity.getClassName();
ComponentName componentInfo = taskInfo.get(0).topActivity;
String packageName=componentInfo.getPackageName();
I used Activity manager to find the top package / activity if this matches the requrements i send a broadcast to the app that will update the info from the db. This can simply be done by registering a broadcast receiver using code in the onResume and Unregister it in OnPause.
So checking the Top package has just become a double check.

Detect when Android app is going to background

In my application I need to detect whether my application is going to background or is switching to another activity of the same application... I know that I have to use the onPause method... but how can I distinguish the two cases?
private static boolean isApplicationGoingToBackground(final Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> tasks = am.getRunningTasks(1);
if (!tasks.isEmpty()) {
ComponentName topActivity = tasks.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
return true;
}
}
return false;
}
UPDATE: getRunningTasks has been declared to not be guaranteed to be accurate.
Call in onStop. onStop gets called after onStart of whatever takes over the screen - if its an activity in the same apk package then you're not going into the background. This does require the GET_TASKS permission.
Or bind to a service onStart & unbind onStop - the service will then be onDestroyed when all your activities are stopped (or track binds vs unbinds if you don't want to rely on onDestroyed getting called - because it might not..).
There is no direct approach to get the app status while background or foreground, but even i have faced this issue, and found the solution with onWindowFocusChanged and onStop. For more details: http://vardhan-justlikethat.blogspot.in/2013/05/android-solution-to-detect-when-android.html

Name of Activity or Receiver that calls the Service

I have a Intent service which is called from either a receiver or an activity. I would like to know the name of the receiver or activity that triggers the service. I don't want to use any extras or flags to pass to the service.
Is there a way to see the activity stack while the code is on the run?
As far as I know there is no way to detect sender of the Intent.
Is there a way to see the activity stack while the code is on the run?
You can use ActivityManager.RunningTaskInfo. Though it doesn't provide much API, it is probably sufficient for your requirements. Pseudocode:
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> runningTasks = activityManager.getRunningTasks(10);
ActivityManager.RunningTaskInfo firstTask = runningTasks.get(0);
String topActivityName = firstTask.topActivity.getShortClassName();
String rootActivityName = firstTask.baseActivity.getShortClassName();
It gives you ability to retrieve the top and root activities of a specific task (AKA. back stack), Note that you need set persimmon GET_TASKS in AndroidManifest.xml.

Categories

Resources