1. 程式人生 > >Android判斷應用是否是從後臺回到前臺

Android判斷應用是否是從後臺回到前臺

很久以前在網上找到的,今天無意間看到這段程式碼,有點忘記了,趕緊記錄下來,以備日後檢視。順便感謝一下當時的大神

private void SetIsRunningForeground() 
{

    var packageName = this.PackageName;
    var activityManager = (ActivityManager)this.GetSystemService(Android.Content.Context.ActivityService);          
    var appProcesses = activityManager.RunningAppProcesses;

    bool flag = false;

    if (appProcesses != null) {
        foreach (var running in appProcesses) {
            if (running.ProcessName.Equals (packageName)) {
                var status = running.Importance;
                if (status == Importance.Visible || status == Importance.Foreground) {
                    flag = true;
                }
            }
        }
    }

    SharedPreferenceManager.SetIsRunningForeground (this, flag);
}   
可以在onStop裡用handler在0.5s(也可以更短)之後呼叫這個方法,然後在onResume裡取sharedPreference的值就知道是否是從後臺回到前臺的了。