傍受アプリがバックグラウンドに切り替えられたかどうか


以前は、アプリケーションがバックグラウンドに切り替えられたかどうかを判断するプログラムが見られましたが...
/** *           * * @return */  
    public boolean isAppOnForeground() {  
        // Returns a list of application processes that are running on the 
        // device 

        ActivityManager activityManager = (ActivityManager) getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE);  
        String packageName = getApplicationContext().getPackageName();  

        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();  
        if (appProcesses == null)  
            return false;  

        for (RunningAppProcessInfo appProcess : appProcesses) {  
            // The name of the process that this object is associated with. 
            if (appProcess.processName.equals(packageName) && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {  
                return true;  
            }  
        }  
        return false;  
    }  

今日はGoogle公式のTrainingを読んでいて、この一節に気づきました.....To be notified when the user exits your UI, implement the onTrimMemory() callback in your Activity classes. You should use this method to listen for the TRIM_MEMORY_UI_HIDDEN level, which indicates your UI is now hidden from view and you should free resources that only your UI uses. Notice that your app receives the onTrimMemory() callback with TRIM_MEMORY_UI_HIDDEN only when all the UI components of your app process become hidden from the user. ….. ユーザーがUIを終了すると、onTrimMemory()が呼び出されます.TRIMも同時に送信されますMEMORY_UI_HIDDEN levelというものは私たちに傍受させます.次のnoticeは、ユーザーがアプリケーションUIコンポーネントを非表示にしている場合にのみ発生します.
テストして、Activityのいずれかに次のように書きます.
@Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if(level == TRIM_MEMORY_UI_HIDDEN){
            Log.e("siyehua", "background...");
        }
    }

ホームキーを押しても、着信があっても、ステータスバーの通知をクリックして他のアプリケーションに入っても、この方法を呼び出し、アプリケーションがバックグラウンドに切り替わるのを正常に傍受することができます.完全なリスニングアプリケーションがバックグラウンドに切り替わったかどうか(^o^)/~Notice:Activityのこの方法を書き換えるだけでよい.他のActivityに切り替えてもメソッドはトリガーされません