1.监听开机广播,可实现开机自启
a、清单文件中注册广播
<receiver
android:name=".service.MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter android:priority="1000">
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent."/>
</intent-filter>
</receiver>
b、广播接收器接收广播
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
//在这里可以去打开你的应用
Intent i = new Intent(context, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
2.监听Home键广播
因为点击Home键或者MENU键在应用内,通过onKeyDown或者onKeyUp是监听不到的;所以要想监听它的状态则需要使用广播
a、Home键的广播监听需要在代码中注册,8.0以上在清单文件中注册好像是收不到的
MyReceiver mHomeKeyReceiver = new MyReceiver();
IntentFilter homeFilter = new IntentFilter();
homeFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
context.registerReceiver(mHomeKeyReceiver, homeFilter);
b、广播接收器中进行自己的处理
public class MyReceiver 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) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
Intent i = new Intent(context, LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}else{
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
//按home键,自己的处理
} else if (reason
.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
}
}
}
}
}
}