Android监听home键的方法
来源:互联网 发布:压缩的js还原 编辑:程序博客网 时间:2024/05/18 02:34
原文地址:http://www.jb51.net/article/79513.htm
如果你的Activity具备这些属性
<activity android:name="com.woyou.activity.HomeActivity" android:launchMode="singleInstance" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.HOME" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter></activity>
当系统点击Home按键的时候,系统会向具有这些属性的Activity发出intent
然后你重写Activity的onNewIntent方法
这个方法就会回调onNewIntent这个方法
已验证可用!
下面这个是我重新写的监听home键的方式,以前写的那些方式都不是很好用。现在的这种方式通过广播的方式监听home键,这个比较好使
1.首先是创建一个广播接受者
private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() { String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; String SYSTEM_HOME_KEY_LONG = "recentapps"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_REASON); if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) { //表示按了home键,程序到了后台 Toast.makeText(getApplicationContext(), "home", 1).show(); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //表示长按home键,显示最近使用的程序列表 } } }};
2.注册监听
可以在Activity里注册,也可以在Service里面
//注册广播registerReceiver(mHomeKeyEventReceiver, new IntentFilter( Intent.ACTION_CLOSE_SYSTEM_DIALOGS));
完整的代码如下:
package com.example.homedemo;import android.os.Bundle;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.text.TextUtils;import android.view.Menu;import android.widget.Toast;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //注册广播 registerReceiver(mHomeKeyEventReceiver, new IntentFilter( Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); } /** * 监听是否点击了home键将客户端推到后台 */ private BroadcastReceiver mHomeKeyEventReceiver = new BroadcastReceiver() { String SYSTEM_REASON = "reason"; String SYSTEM_HOME_KEY = "homekey"; String SYSTEM_HOME_KEY_LONG = "recentapps"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) { String reason = intent.getStringExtra(SYSTEM_REASON); if (TextUtils.equals(reason, SYSTEM_HOME_KEY)) { //表示按了home键,程序到了后台 Toast.makeText(getApplicationContext(), "home", 1).show(); }else if(TextUtils.equals(reason, SYSTEM_HOME_KEY_LONG)){ //表示长按home键,显示最近使用的程序列表 } } } };}
0 0