相信有不少朋友在開發(fā)過程中需要監(jiān)聽HOME鍵的需求,現(xiàn)本人將代碼奉上,希望對大家有所幫助!
創(chuàng)新互聯(lián)是一家集網(wǎng)站建設(shè),連云企業(yè)網(wǎng)站建設(shè),連云品牌網(wǎng)站建設(shè),網(wǎng)站定制,連云網(wǎng)站建設(shè)報價,網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,連云網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強企業(yè)競爭力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時我們時刻保持專業(yè)、時尚、前沿,時刻以成就客戶成長自我,堅持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實用型網(wǎng)站。
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;
// 回調(diào)接口
public interface OnHomePressedListener
{
public void onHomePressed();
public void onHomeLongPressed();
}
public HomeWatcher(Context context)
{
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
/**
* 設(shè)置監(jiān)聽
*
* @param listener
*/
public void setOnHomePressedListener(OnHomePressedListener listener)
{
mListener = listener;
mRecevier = new InnerRecevier();
}
/**
* 開始監(jiān)聽,注冊廣播
*/
public void startWatch()
{
if (mRecevier != null)
{
mContext.registerReceiver(mRecevier, mFilter);
}
}
/**
* 停止監(jiān)聽,注銷廣播
*/
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();
}
}
}
}
}
}
}
調(diào)用時注意:
在初始化調(diào)用(如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();// 在銷毀時停止監(jiān)聽,不然會報錯的。