Android监听Home键的完美解决方案
相信有不少朋友在开发过程中需要监听HOME键的需求,现本人将代码奉上,希望对大家有所帮助!
创新互联是一家集网站建设,连云企业网站建设,连云品牌网站建设,网站定制,连云网站建设报价,网络营销,网络优化,连云网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
public class HomeWatcher
{
private static final String TAG = "HomeWatcher";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerRecevier mRecevier;
// 回调接口
public interface OnHomePressedListener
{
public void onHomePressed();
public void onHomeLongPressed();
}
public HomeWatcher(Context context)
{
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
/**
* 设置监听
*
* @param listener
*/
public void setOnHomePressedListener(OnHomePressedListener listener)
{
mListener = listener;
mRecevier = new InnerRecevier();
}
/**
* 开始监听,注册广播
*/
public void startWatch()
{
if (mRecevier != null)
{
mContext.registerReceiver(mRecevier, mFilter);
}
}
/**
* 停止监听,注销广播
*/
public void stopWatch()
{
if (mRecevier != null)
{
mContext.unregisterReceiver(mRecevier);
}
}
/**
* 广播接收者
*/
class InnerRecevier extends BroadcastReceiver
{
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
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 (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS))
{
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null)
{
Log.i(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null)
{
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY))
{
// 短按home键
mListener.onHomePressed();
}
else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS))
{
// 长按home键
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
调用时注意:
在初始化调用(如onCreate)时添加如下代码:
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener()
{
@Override
public void onHomePressed()
{
//按了HOME键
}
@Override
public void onHomeLongPressed()
{
//长按HOME键
}
});
mHomeWatcher.startWatch();
在程序销毁时(如:onDestroy)时添加如下代码:
if(mHomeWatcher != null)
mHomeWatcher.stopWatch();// 在销毁时停止监听,不然会报错的。
网站栏目:Android监听Home键的完美解决方案
标题路径:http://cdiso.cn/article/jsoegg.html