一、监听home键首先定义一个广播接受者
HomeKeyReceiver
package com.kale.floattest; import com.kale.floattest.service.DrawService; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class HomeKeyReceiver extends BroadcastReceiver{ static final String SYSTEM_REASON = "reason"; static final String SYSTEM_HOME_KEY = "homekey";// home key static final String SYSTEM_RECENT_APPS = "recentapps";// long home key @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 (reason != null) { if (reason.equals(SYSTEM_HOME_KEY)) { Log.e("homekey", "home键被点击"); context.stopService(new Intent(context,DrawService.class)); } else if (reason.equals(SYSTEM_RECENT_APPS)) { Log.e("homekey", "长按home键"); } } } } }
这里的事件我写了关闭一个服务,当然大家可以自由发挥。下面是在服务中注册
// 监听HOME键 HomeKeyReceiver receiver; @Override public void onCreate() { super.onCreate(); // 注册监听home键广播 receiver = new HomeKeyReceiver(); registerReceiver(receiver, new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)); } @Override public void onDestroy() { super.onDestroy(); //取消监听home键 unregisterReceiver(receiver); }
二、模拟home键(执行代码后就等于点击了home键)
protected void virtualHome() { //模拟HOME键 Intent i= new Intent(Intent.ACTION_MAIN); i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); //如果是服务里调用,必须加入new task标识 i.addCategory(Intent.CATEGORY_HOME); startActivity(i); }