android 屏蔽电源键,home键

2019-07-13 23:34发布

 Android中屏蔽"电源键长按"、"Home键"、"Home键长按"
这几个“按钮”的触发,都会产生一个Action == Intent.ACTION_CLOSE_SYSTEM_DIALOGS的通知 区分他们三个的不同事件的参数,就是随着Intent带过来的reason字符串,分别对应 "电源键长按"(globalscreen)、"Home键"(homekey)、"Home键长按"(recentapps) 说破了就这么简单,直接上代码了。 package com.jumpinus.test; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; public class MainActivity extends Activity { private MyBroadCastReceiver myBroadCastReceiver; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); myBroadCastReceiver = new MyBroadCastReceiver(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); System.out.println("I'm coming, myBroadCastReceiver注册了!"); registerReceiver(myBroadCastReceiver, intentFilter); } private class MyBroadCastReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { //你自己先把 reasons == homekey 和 长按homekey 排除,剩下的做下面的处理 String reason = intent.getStringExtra("reason"); if (intent.getAction().equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)){ System.out.println("Intent.ACTION_CLOSE_SYSTEM_DIALOGS : " + intent.getStringExtra("reason")); if (intent.getExtras()!=null && intent.getExtras().getBoolean("myReason")){ myBroadCastReceiver.abortBroadcast(); }else if (reason != null){ if (reason.equalsIgnoreCase("globalactions")){ //屏蔽电源长按键的方法: Intent myIntent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); myIntent.putExtra("myReason", true); context.sendOrderedBroadcast(myIntent, null); System.out.println("电源 键被长按"); }else if (reason.equalsIgnoreCase("homekey")){ //屏蔽Home键的方法 //在这里做一些你自己想要的操作,比如重新打开自己的锁屏程序界面,这样子就不会消失了 System.out.println("Home 键被触发"); }else if (reason.equalsIgnoreCase("recentapps")){ //屏蔽Home键长按的方法 System.out.println("Home 键被长按"); } } } } } @Override protected void onPause() { // TODO Auto-generated method stub super.onPause(); System.out.println("I get out, myBroadCastReceiver注销了!"); unregisterReceiver(myBroadCastReceiver); } }

效果图: