思路:当HOME键被按下的时候,系统会发出广播,我们写一个自定义的广播接收器,就可以拦截到它。
自定义一个广播接收器:
class HomePressReceiver extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
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 && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
Log.d(TAG, "onReceive: home key pressed");
}
}
}
}
先定义一个IntentFilter用来过滤指定的广播,一个接收器。
private IntentFilter homeKeyFilter;
private HomePressReceiver homePressReceiver;
private String TAG ="aiden: "; //debug用
接下来,在onCreate中,添加:
homeKeyFilter = new IntentFilter();
homeKeyFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
homePressReceiver = new HomePressReceiver();
registerReceiver(homePressReceiver, homeKeyFilter);
在退出APP的时候,需要反注册这个接收器。所以在onDestroy中添加:
if(homePressReceiver != null){
try {
unregisterReceiver(homePressReceiver);
} catch (Exception e) {
Log.e(TAG, "unregisterReceiver homePressReceiver failure :"+e.getCause());
}
}
完整代码如下:
package com.aiden.homekeydetection;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private IntentFilter homeKeyFilter;
private HomePressReceiver homePressReceiver;
private String TAG ="aiden: ";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
homeKeyFilter = new IntentFilter();
homeKeyFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
homePressReceiver = new HomePressReceiver();
registerReceiver(homePressReceiver, homeKeyFilter);
}
public void onDestroy() {
if(homePressReceiver != null){
try {
unregisterReceiver(homePressReceiver);
} catch (Exception e) {
Log.e(TAG, "unregisterReceiver homePressReceiver failure :"+e.getCause());
}
}
super.onDestroy();
}
class HomePressReceiver extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
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 && reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
Log.d(TAG, "onReceive: home key pressed");
}
}
}
}
}
不需要在AndroidManifest.xml中做任何修改。
测试通过。
网友评论