Android实现广播监听HOME键操作

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>


先写了个Service,在服务中通过广播来监听HOME键操作:

public class HomeService extends Service{
private MonitoHomeReceiver mHomeBroadcastReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mHomeBroadcastReceiver = new MonitoHomeReceiver();
/**
* Android对屏幕下方常用按键消息处理是不一致的:
* 1、搜索按键的消息在onKeyDown或者onKeyUp中接收;
* 2、菜单按键的消息在onCreateOptionsMenu、onKeyDown或onKeyUp方法中接收;
* 3、返回按键的消息可以在onBackPressed、onKeyDown或onKeyUp方法中接收。
* 对于Home按键消息的处理,既不能通过onKeyDown、onKeyUp接收到,android也没有提供专有的方法接收按键消息
* 但办法总是有的,点击Home按键时都会发出一个action为Intent.ACTION_CLOSE_SYSTEM_DIALOGS的广播,通过注册它来监听Home按键消息
*/
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mHomeBroadcastReceiver, homeFilter);
}
public class MonitoHomeReceiver extends BroadcastReceiver{
final String HOME_DIALOG_REASON = "homereason";
final String HOME_DIALOG_REASON_HOME = "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(HOME_DIALOG_REASON);
if (reason != null && reason.equals(HOME_DIALOG_REASON_HOME)) {
Toast.makeText(getApplicationContext(), "点击Home键", Toast.LENGTH_SHORT).show();
return;
}
}
}


}

@Override
public void onDestroy() {
unregisterReceiver(mHomeBroadcastReceiver);
mHomeBroadcastReceiver = null;
super.onDestroy();
}
}

然后在Activity中启动Service:


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**按钮点击事件*/
findViewById(R.id.test_home_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,HomeService.class);
startService(intent);
}
});
}
}

最后就是个简单的布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/test_home_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="测试Home键" />

</LinearLayout>

最后不要忘记在AndroidManifest.xml中用<Service></Service>标签注册HomeService 服务。