Home键监听与电源power键监听

2019-07-14 03:25发布

Home键监听与电源power键监听
1、新建广播工具类
HomeReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;


public class HomeReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
       String action =intent.getAction();
       if(action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){
      String reason=intent.getStringExtra("reason");
     
          
           if(reason !=null){
          if(reason.equals("homekey")){
          MyAplication.homeKey=true;
          Log.d("wzg", "homekey");
          }else if(reason.equals("recentapps")){
          MyAplication.homeKey=true;
          Log.d("wzg", "recentapps");
          }
          
           }
       }
   /**     
    * 1) 待机:
    *    广播消息:android.intent.action.SCREEN_OFF (代码)
    * 2) 唤醒:
    *    广播消息:android.intent.action.SCREEN_ON (代码)
    * 3) 关机:
    *    广播消息:android.intent.action.ACTION_SHUTDOWN (XML或代码)*/
       if(Intent.ACTION_SCREEN_OFF.equals(action)) {//捕获power键
      MyAplication.homeKey=true;
      Log.d("wzg", "WAKE_LOCK");
       }  
}


}


2、activity.java 类中 注册广播,使用广播、释放广播
   在activity onCreate()方法里面注册使用
public class activity extends Activity{
  private HomeReceiver receiverHome=new HomeReceiver();
private IntentFilter filterHome=null;
 
public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity);
   filterHome = new IntentFilter();
filterHome.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
filterHome.addAction(Intent.ACTION_SCREEN_OFF);
registerReceiver(receiverHome, filterHome);
}

public void onDestroy()
{
  if(receiverHome !=null)
unregisterReceiver(receiverHome);
}
}


3、添加权限 AndroidManifest.xml