這個問題已經被問喜歡百倍運行,但所有我能罰有使用檢查,如果我的應用程序在後臺
getRunningAppProcesses()
相同的答案不上棒棒堂
正常工作所以它有一個完全可靠的方法來知道我的應用程序是否在背景中活着?
謝謝
編輯:
這就是我用它來檢查,如果在前臺應用程序:使用
喜好:
public static void setStartingActivity(Context context, boolean isStartingActivity) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("isStartingActivity", isStartingActivity).apply();
}
public static boolean isStartingActivity(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("isStartingActivity", false);
}
public static void setAppRunningInForeground(Context context, boolean isRunning) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean("AppIsRunningInForeground", isRunning).apply();
}
public static boolean isAppRunningForeground(Context context) {
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean("AppIsRunningInForeground", false);
}
開始活動:
Utility.PreferencesManager.setStartingActivity(getApplicationContext(), true);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
調用OnStop和在onStart實現:
@Override
protected void onStart() {
super.onStart();
Log.e("Debugging", "MainActivity onStart");
Utility.PreferencesManager.setAppRunningInForeground(getApplicationContext(), true);
}
@Override
protected void onStop() {
super.onStop();
Log.e("Debugging", "MainActivity onStop");
if (!Utility.PreferencesManager.isStartingActivity(getApplicationContext()))
Utility.PreferencesManager.setAppRunningInForeground(getApplicationContext(), false);
else
Utility.PreferencesManager.setStartingActivity(getApplicationContext(), false);
}
您是否嘗試過[onPause](https://developer.android.com/guide/components/activities/activity-lifecycle.html#onpause) – Derek
我認爲這是尋找的內容:http:// stackoverflow。 com/questions/30619349/android-5-1-1-and-above-getrunningappprocesses-returns-my-application-packag –
通常,無論您在此嘗試完成什麼,都有更好的解決方案。你打算如何處理關於你是處於前景還是背景的信息? – CommonsWare