home鍵監聽(Android應用切換到後臺監聽)

珊瑚瞧發表於2015-10-26

1、通過註冊廣播監聽

package country.company.project.util;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

public class HomeWatcher {

    static final String TAG = "hg";
    private Context mContext;
    private IntentFilter mFilter;
    private OnHomePressedListener mListener;
    private InnerRecevier mRecevier;

    public HomeWatcher(Context context) {
        mContext = context;
        mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    public void setOnHomePressedListener(OnHomePressedListener listener) {
        mListener = listener;
        mRecevier = new InnerRecevier();
    }

    public void startWatch() {
        if (mRecevier != null) {
            mContext.registerReceiver(mRecevier, mFilter);
        }
    }

    public void stopWatch() {
        if (mRecevier != null) {
            mContext.unregisterReceiver(mRecevier);
        }
    }

    class InnerRecevier extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    Log.e(TAG, "action:" + action + ",reason:" + reason);
                    if (mListener != null) {
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                            // home鍵
                            mListener.onHomePressed();
                        } else if (reason
                                .equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                            // 長按home鍵
                            mListener.onHomeLongPressed();
                        }
                    }
                }
            }
        }
    }
}

package country.company.project.util;

public interface OnHomePressedListener {
    public void onHomePressed();

    public void onHomeLongPressed();
}

在Activity的onCreate()或者其它你需要的地方註冊監聽器

package country.company.project.util;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import country.company.project.util.R;

public class HomeWatcherActivity extends Activity {
    private final String TAG = "hg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.about);
        HomeWatcher mHomeWatcher = new HomeWatcher(this);
        mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
            @Override
            public void onHomePressed() {
                Log.e(TAG, "onHomePressed");
            }
            @Override
            public void onHomeLongPressed() {
                Log.e(TAG, "onHomeLongPressed");
            }
        });
        mHomeWatcher.startWatch();
    }
}

2、通過activity的一個生命週期方法:

protected void onUserLeaveHint ()

Since: API Level 3
Called as part of the activity lifecycle when an activity is about to go into the background as the result of user choice. 
For example, when the user presses the Home key, onUserLeaveHint() will be called, but when an incoming phone call causes the in-call Activity to be automatically brought to the foreground,
onUserLeaveHint() will not be called on the activity being interrupted. In cases when it is invoked, this method is called right before the activity's onPause() callback.
This callback and onUserInteraction() are intended to help activities manage status bar notifications intelligently; specifically, for helping activities determine the proper time to cancel a notfication.

從文件來看,這個方法似乎就是為了按下Home鍵時這樣的場景設計的。
這樣,在onUserLeaveHint裡發出系統通知即可。
但是問題又來了,如果啟動應用,從一個activity依次呼叫startActivity,finish關閉自己,啟動一個新的activity時,onUserLeaveHint也會被呼叫….

再次翻閱文件,發現Intent中的一個Flag:

public static final int FLAG_ACTIVITY_NO_USER_ACTION

Since: API Level 3
If set, this flag will prevent the normal onUserLeaveHint() callback from occurring on the current frontmost activity before it is paused as the newly-started activity is brought to the front.

Typically, an activity can rely on that callback to indicate that an explicit user action has caused their activity to be moved out of the foreground. 
The callback marks an appropriate point in the activity's lifecycle for it to dismiss any notifications that it intends to display "until the user has seen them," such as a blinking LED.
If an activity is ever started via any non-user-driven events such as phone-call receipt or an alarm handler, this flag should be passed to Context.startActivity, ensuring that the pausing activity does not think the user has acknowledged its notification.

這正是我想要的,這樣,在啟動activity時,往intent中加上這個flag,onUserLeaveHint就不會再被呼叫了

這種方法不太好得原因是每一個start的Activity都需要新增flag才能用於應用切換到後臺的判斷,專案大的時候比較麻煩

相關文章