標籤:android開發 broadcastreceiver
先寫了個Service,在服務中通過廣播來監聽HOME鍵操作:
public class HomeService extends Service{
private MonitoHomeReceiver mHomeBroadcastReceiver;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mHomeBroadcastReceiver = new MonitoHomeReceiver();
/**
* Android對螢幕下方常用按鍵訊息處理是不一致的:
* 1、搜尋按鍵的訊息在onKeyDown或者onKeyUp中接收;
* 2、菜單按鍵的訊息在onCreateOptionsMenu、onKeyDown或onKeyUp方法中接收;
* 3、返回按鍵的訊息可以在onBackPressed、onKeyDown或onKeyUp方法中接收。
* 對於Home按鍵訊息的處理,既不能通過onKeyDown、onKeyUp接收到,android也沒有提供專有的方法接收按鍵訊息
* 但辦法總是有的,點擊Home按鍵時都會發出一個action為Intent.ACTION_CLOSE_SYSTEM_DIALOGS的廣播,通過註冊它來監聽Home按鍵訊息
*/
IntentFilter homeFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
registerReceiver(mHomeBroadcastReceiver, homeFilter);
}
public class MonitoHomeReceiver extends BroadcastReceiver{
final String HOME_DIALOG_REASON = "homereason";
final String HOME_DIALOG_REASON_HOME = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(HOME_DIALOG_REASON);
if (reason != null && reason.equals(HOME_DIALOG_REASON_HOME)) {
Toast.makeText(getApplicationContext(), "點擊Home鍵", Toast.LENGTH_SHORT).show();
return;
}
}
}
}
@Override
public void onDestroy() {
unregisterReceiver(mHomeBroadcastReceiver);
mHomeBroadcastReceiver = null;
super.onDestroy();
}
}
然後在Activity中啟動Service:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/**按鈕點擊事件*/
findViewById(R.id.test_home_btn).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,HomeService.class);
startService(intent);
}
});
}
}
最後就是個簡單的布局檔案:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/test_home_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="測試Home鍵" />
</LinearLayout>
最後不要忘記在AndroidManifest.xml中用<Service></Service>標籤註冊HomeService 服務。
Android實現廣播監聽HOME鍵操作