前言
最近在写一个项目模块,需要监听Android手机的Home键,但是Home键属于手机系统键,在Activity当中监听其他的键Google给我提供了相应的方法,唯独Home键没有提供,那是否有什么方法可以监听Home键呢?答案是有的,用注册广播的方式来监听Home键,除了这一种方式以外,其实还有其他几种方式,但是个人认为这种方式比较好,所以在这里我就只针对广播的方式来监听Home键的讲解,若有不妥的地方,还望指出。
以下是代码部分
package cn.zt.demo.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class HomeKeyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("HomeKey按下");
}
}
}
package cn.zt.demo.activity;
import cn.zt.demo.broadcastreceiver.HomeKeyBroadCastReceiver;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
public class HomeKeyEventActivity extends Activity {
private HomeKeyBroadCastReceiver mReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homekey_event);
registerHomeKeyReceiver();
}
private void registerHomeKeyReceiver() {
mReceiver = new HomeKeyBroadCastReceiver();
registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
}
@Override
protected void onDestroy() {
super.onDestroy();
if(mReceiver != null){
unregisterReceiver(mReceiver);
}
}
}
以上是利用广播监听HomeKey按下事件的全部内容,如有欠妥,还望指出