1. 程式人生 > 實用技巧 >android監聽Home鍵

android監聽Home鍵

一、使用註冊廣播監聽home鍵、多工鍵

class InnerRecevier extends BroadcastReceiver {

  final String SYSTEM_DIALOG_REASON_KEY = "reason";
 
  final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
 
  final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
 
  @Override
  public void onReceive(Context context, Intent intent) {
   String action 
= intent.getAction(); if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) { String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY); if (reason != null) { if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) { Toast.makeText(MainActivity.this, "Home鍵被監聽", Toast.LENGTH_SHORT).show(); }
else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) { Toast.makeText(MainActivity.this, "多工鍵被監聽", Toast.LENGTH_SHORT).show(); } } } }

在Activity中的onCreate()方法中註冊廣播,程式碼如下:

@Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
 
  
//建立廣播 InnerRecevier innerReceiver = new InnerRecevier(); //動態註冊廣播 IntentFilter intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); //啟動廣播 registerReceiver(innerReceiver, intentFilter); }