在mainActivity中
public class MainActivity extends Activity {
private HomeKeyDown mHomeKeyDown;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if( mHomeKeyDown == null ) {
mHomeKeyDown = new HomeKeyDown( this );
mHomeKeyDown.setOnHomePressedListener( new OnHomePressedListener() {
@Override
public void onHomePressed() {
// 需要写的逻辑
System.out.println( "按下home" );
}
});
mHomeKeyDown.startReceiver();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
mHomeKeyDown.stopReceiver();
}
public void onBackPressed() {
// 需要写的逻辑
System.out.println( "退出程序" );
};
}
在HomeKeyDown类中
/**
* Home键监听
*/
public class HomeKeyDown {
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
// 回调接口
public interface OnHomePressedListener {
public void onHomePressed();
}
public HomeKeyDown(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
/**
* 设置监听
*/
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mRecevier = new InnerRecevier();
}
/**
* 设置监听,注册广播接收者
*/
public void startReceiver() {
if (mRecevier != null) {
mContext.registerReceiver(mRecevier, mFilter);
}
}
/**
* 停止监听,取消注册
*/
public void stopReceiver() {
if (mRecevier != null) {
mContext.unregisterReceiver(mRecevier);
}
}
/**
* 广播接收者
*/
class InnerRecevier extends BroadcastReceiver {
final String REASON_KEY = "reason";
final String 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(REASON_KEY);
if (reason != null) {
if (mListener != null) {
if (reason.equals(HOME_KEY)) {
mListener.onHomePressed();
}
}
}
}
}
}
}
不太会写博客......大概就是这个样子,感谢同学郑总提供的方法.