i have this thread:
public void run() {
try {
while(isThereActivityRunning()) {
results = sendGetMessage();
b.putString("results", results);
receiver.send(2, b);
ConnectionThread.sleep(timeInterval);
}
} catch (InterruptedException e) {
results = e.toString();
}
Log.d("Service", "Serivce Stoped");
}
and a function that checks if i have any activity running:
private boolean isThereActivityRunning()
{
String activity;
ActivityManager activityManager = (ActivityManager)context.getSystemService (Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> services = activityManager.getRunningTasks(Integer.MAX_VALUE);
for (int i1 = 0; i1 < services.size(); i1++) {
activity = services.get(i1).topActivity.toString();
Log.d("Activity", activity);
if (activity.contains(context.getString(R.string.app_name))
return true;
}
return false;
}
i want my thread to stop when there is no activity running (which mean for me that the application is closed) and from some reason i always get “true” from function even when my activity is not displayed.. what is wrong ?
You can change your is activity running to be this:
This should return false once your application is not in the foreground. In Android you will not receive a notification to let you know when the application is actually killed. Another note is this should be checked at the earliest in the onStop of the activity because before that the activity will still report as in the foreground.