This is the scenario...
- App is opened
- User clicks on a button that starts a service.
- User presses home key and then long presses home key and clears application from task list.
- Service continues to run, although app has closed.
How from the runnning service can I determine whether that app has been killed or not? Is this possible?
I think this what you are looking for:
private boolean isAppRunning() {
ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
for (RunningTaskInfo task : manager.getRunningTasks(Integer.MAX_VALUE)) {
if ("com.example.YourLauncherActivityClassFullName".equals(task.baseActivity.getClassName())) {
return true;
}
}
return false;
}
The only thing you need to provide is full launcher activity class name of your app.
first you should start a service, that should look after particular time that whether your activity is running or not. for that you could use Alarm Manager to check after some time.
To check whether your activity is running or not, you should use,
ArrayList<String> runningactivities = new ArrayList<String>();
ActivityManager activityManager = (ActivityManager)getBaseContext().getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
runningactivities.add(0,services.get(i1).topActivity.toString());
}
if(runningactivities.contains("ComponentInfo{com.app/com.app.main.MyActivity}")==true){
Toast.makeText(getBaseContext(),"Activity is in foreground, active",1000).show();
}
In you main (first) activity:
public static boolean isRunning;
@Override
public void onCreate(Bundle savedInstanceState) {
isRunning = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
...
}
@Override
public void finish() {
isRunning = false;
super.finish();
}
check isRunning flag in your service.