我有这个帖子:
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");
}
以及检查我是否正在运行任何活动的函数:
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;
}
我希望我的线程在没有活动运行时停止(这对我意味着应用程序已关闭)并且由于某种原因我甚至在我的活动未显示时总是从“函数”获得“真实”..出了什么问题?
答案 0 :(得分:0)
您可以将正在运行的活动更改为:
private boolean isThereActivityRunning(){
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null)
return false;
final String packageName = context.getPackageName();
for (RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
return true;
}
}
return false;
}
一旦您的应用程序不在前台,这应该返回false。在Android中,您不会收到通知,以便在应用程序实际被杀死时通知您。另一个注意事项是,应该最早在活动的onStop上检查,因为在此之前,活动仍然会在前台报告。