Android 监听home,menu键

1.
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class Homelister {
 private Context mContext;
 private IntentFilter mFilter;
 private OnHomePressedListener mListener;
 
 private InnerRecevier mRecevier;
 public interface OnHomePressedListener {
  public void onHomePressed();//home
  
  public void onHomeLongPressed();//经测试在华为上,这个是最右边的按键,根据不通手机
 }
 
 public Homelister(Context context){
  mContext=context;
  mFilter=new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
 }
 
 //监听
 public void OnHomePressedListener(OnHomePressedListener listenre){
  mListener=listenre;
  mRecevier=new InnerRecevier();
  
 }
 
 //开启广播
 public void startListter(){
  if(mRecevier!=null){
   mContext.registerReceiver(mRecevier, mFilter);
  }
  
 }
 
 //停止广播
 public void stopListter(){
  if(mRecevier!=null){
   mContext.unregisterReceiver(mRecevier);
  }
 }
 
 
 class InnerRecevier extends BroadcastReceiver{
  @Override
  public void onReceive(Context context, Intent intent) {
   // TODO Auto-generated method stub
   String action=intent.getAction();//根据不通的action做不通的操作
   if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
    String reason= intent.getStringExtra("reason");
    if(reason!=null){
     if(mListener!=null){
      if(reason.equals("homekey")){
       mListener.onHomePressed();
      }else if(reason.equals("recentapps")) {
       mListener.onHomeLongPressed();
      }
     }
    }
   }
   
   
  }
  
 }
 2.  private void registerHomeListener() {
  mylis = new Homelister(this);
  mylis.OnHomePressedListener(new OnHomePressedListener() {
   @Override
   public void onHomePressed() {
    // TODO Auto-generated method stub
    System.out.println("xsl="+"OnHome");
    SDKInterface.upQuitState("OnHome");
   }
   
   @Override
   public void onHomeLongPressed() {
    // TODO Auto-generated method stub
    System.out.println("xsl="+"OnMenu");
    SDKInterface.upQuitState("OnMenu");
   }
  });
  mylis.startListter();
 }
 需要在onCreate里面调用当进入页面就开启
3. public void onPause() {
  mylis.stopListter();
在适当的时候要注销,onRestart 里面再次开启

你可能感兴趣的:(android,监听手机Home)