监听Home键和返回键

创建homereceiver
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

public class HomeKeyEventBroadCastReceiver extends BroadcastReceiver {

    static final String SYSTEM_REASON = "reason";
    static final String SYSTEM_HOME_KEY = "homekey";//home key
    static final String SYSTEM_RECENT_APPS = "recentapps";//long home key

    private HomeKeyCallBack homeKeyCallBack;

    @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_REASON);
            if (reason != null) {
                if (reason.equals(SYSTEM_HOME_KEY)) {
                    // home key处理点
                    if (homeKeyCallBack != null) {
                        homeKeyCallBack.onHomeKey();
                    }

                } else if (reason.equals(SYSTEM_RECENT_APPS)) {
                    // long home key处理点
                }
            }
        }
    }

    public void setHomeKeyCallBack(HomeKeyCallBack homeKeyCallBack) {
        this.homeKeyCallBack = homeKeyCallBack;
    }

    public void registerReceiver(Context context){
        context.registerReceiver(this, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
    }

    public void unRegisterReceiver(Context context) {
        context.unregisterReceiver(this);
    }

    public interface HomeKeyCallBack {
        public void onHomeKey();
    }
}  
在service中 实现HomeKeyCallBack
@Override
public void onHomeKey() {//处理home按键
//发消息处理自己的操作
    //MessageObject msgObject = new MessageObject(SpeechConstant.UI_DIALOG_STATE.SEND_EXIT_DIALOG_ACTION, null, null);
    //MessageHandler.getInstance(SpeechService.this).sendMessage(msgObject);
}

你可能感兴趣的:(android)