Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Activity is running from Service

How can a Service check if one of it's application's Activity is running in foreground?

like image 682
Taranfx Avatar asked Aug 29 '12 06:08

Taranfx


2 Answers

Use the below method with your package name. It will return true if any of your activities is in foreground.

public boolean isForeground(String myPackage) {     ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);     List<ActivityManager.RunningTaskInfo> runningTaskInfo = manager.getRunningTasks(1);      ComponentName componentInfo = runningTaskInfo.get(0).topActivity;     return componentInfo.getPackageName().equals(myPackage); } 

Update:

Add Permission:

<uses-permission android:name="android.permission.GET_TASKS" /> 
like image 111
Rasel Avatar answered Oct 19 '22 17:10

Rasel


Use SharedPreferences to save the status of your app in onResume, onPause etc.

like so:

 @Override public void onPause() {     super.onPause();     PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", false).commit(); }  @Override public void onDestroy() {     super.onDestroy();     PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", false).commit(); }  @Override public void onResume() {     super.onResume();     PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean("isActive", true).commit(); } 

and then in the service:

if (PreferenceManager.getDefaultSharedPreferences(this).getBoolean("isActive", false)) {             return; } 

i used both onPause and onDestroy because sometimes it jumps straight to onDestroy:) it's basically all voodoo

anyway, hope that helps someone

like image 21
eiran Avatar answered Oct 19 '22 18:10

eiran