HOME键

拦截

重写onAttachedToWindow

4.0+报错

public void onAttachedToWindow() {
    this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
    super.onAttachedToWindow();
}
重写onKeyDown

监听不到HOME键

// 自定标志
public static final int FLAG_HOMEKEY_DISPATCHED = 0x80000000; 

/**
 * 加载视图
 *
 * @param savedInstanceState 状态保存
 */
@Override
protected void initContentView(Bundle savedInstanceState) {
    // 关键代码
    this.getWindow().setFlags(FLAG_HOMEKEY_DISPATCHED, FLAG_HOMEKEY_DISPATCHED);
    //hideStatusNavigationBar();
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
    ReceiveMessageHandle.observeReceiveMessage(this, true);
    ObserveMessageStatus.observeMsgStatus(true);
    ObserveMessageReceipt.observeMessageReceipt(true);
    ObserveTeamMessageReceipt.observeTeamMessageReceipt(true);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (event.getKeyCode() == KeyEvent.KEYCODE_HOME) {            
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
曲线救国

HomeInterceptReceiver

package com.xalikai.bnmdstudentend.kit;

import android.app.Activity;
import android.app.Application;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import util.ActivitySuperviseUtils;

/**
 * Created on 2019/4/9.
 *
 * @author 郑少鹏
 * @desc HOME键拦截广播
 */
public class HomeInterceptReceiver extends BroadcastReceiver {
    /**
     * 应用Context对象
     */
    private Application application;

    public HomeInterceptReceiver(Application application) {
        this.application = application;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // 按Home键发ACTION_CLOSE_SYSTEM_DIALOGS广播
        if (action != null && action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
            Activity activity = ActivitySuperviseUtils.getTopActivityInstance();
            if (activity != null) {
                String className = activity.getClass().getCanonicalName();
                if (className != null) {
                    Intent intent1 = new Intent();
                    intent1.setClassName(application.getPackageName(), className);
                    application.startActivity(intent1);
                }
            }
        }
    }
}

主代码

HomeInterceptReceiver innerHomeInterceptReceiver = new HomeInterceptReceiver(App.getInstance());
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(innerHomeInterceptReceiver, intentFilter);

按下

按BACK键后重启速度很快,按Home键后约5秒才能看到。参考。

你可能感兴趣的:(android)