先自定义一个广播类
public class ScreenBroadcastReceiver extends BroadcastReceiver {
private final static String TAG = "ScreenBroadcastReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.e(TAG, "广播Action = " + action);
if (action.equals(Intent.ACTION_SCREEN_OFF)) {
Log.e(TAG, "锁屏");
context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
Log.e(TAG, "解锁");
context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
} else if (action.equals(Intent.ACTION_USER_PRESENT)) {
Log.e(TAG, "开屏");
context.getApplicationContext().startService(new Intent(context.getApplicationContext(), RtmService.class));
}
}
}
然后在Application中进行动态注册
private ScreenBroadcastReceiver mScreenBroadcastReceiver;
if (null == mScreenBroadcastReceiver)
mScreenBroadcastReceiver = new ScreenBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(Intent.ACTION_SCREEN_ON); //解锁
intentFilter.addAction(Intent.ACTION_SCREEN_OFF); //锁屏
intentFilter.addAction(Intent.ACTION_USER_PRESENT); //开屏
registerReceiver(mScreenBroadcastReceiver, intentFilter);
因为是动态注册所以无需在AndroidManifest.xml中进行注册
网友评论