现在我正在使用 BackGround服务继续我的通知部分,即使在我的应用程序停止或我使用其他应用程序之后服务也会运行
但现在我需要的是,如果应用程序在5分钟或更长时间内未激活,则 BackGround服务应自动停止。
我已经使用了以下内容,但没有使用它仍然是相同的:
public class ForegroundCheckTask extends AsyncTask<Context, Void, Boolean> {
@Override
protected Boolean doInBackground(Context... params) {
final Context context = params[0].getApplicationContext();
return isAppOnForeground(context);
}
private boolean isAppOnForeground(Context context) {
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;
}
}
尝试了很多修复,但仍然是相同的是有任何其他去请帮助我的朋友解决这个问题。
更新
public class ApplicationActivity implements Application.ActivityLifecycleCallbacks {
// I use four separate variables here. You can, of course, just use two and
// increment/decrement them instead of using four and incrementing them all.
public static int resumed;
public static int paused;
public static int started;
public static int stopped;
public static boolean stopStatus = false;
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
++resumed;
}
@Override
public void onActivityPaused(Activity activity) {
++paused;
android.util.Log.w("test", "application is in foreground: " + (resumed > paused));
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityStarted(Activity activity) {
++started;
}
@Override
public void onActivityStopped(Activity activity) {
++stopped;
stopStatus = true;
android.util.Log.w("test", "application is visible: " + (started > stopped));
}
public class MyApplication extends Application {
@Override
public void onCreate() {
// Simply add the handler, and that's it! No need to add any code
// to every activity. Everything is contained in MyLifecycleHandler
// with just a few lines of code. Now *that's* nice.
registerActivityLifecycleCallbacks(new ApplicationActivity());
}
}
答案 0 :(得分:0)
我会采用另一种方法:
答案 1 :(得分:0)
目前还不清楚你到底要做什么以及为什么。如果您的服务是Service
的子类,那么它可以自行停止,或者您的活动可以明确地停止它。如果您的活动与其绑定而不是调用startService()
,则系统可以在所有客户端未绑定后自动停止服务。构建Android以便它可以根据需要启动和停止它们。请注意,即使您的服务和所有活动都已停止,您的应用程序也会一直存在,直到系统需要资源为止。