Home键监听与电源power键监听

本文介绍了如何在Android中实现对Home键和Power键的监听。通过创建`HomeReceiver`广播接收器,捕获`ACTION_CLOSE_SYSTEM_DIALOGS`和`ACTION_SCREEN_OFF`动作,从而在用户按下Home键或电源键时触发相应操作。在`activity`的`onCreate()`中注册广播接收器,并在`onDestroy()`中释放。同时,需要在`AndroidManifest.xml`中添加`WAKE_LOCK`权限。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
<uses-permission android:name="android.permission.WAKE_LOCK" /> 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值