在网上了解了一个防止Service在息屏后被杀死的思路,就是监听屏幕亮灭的广播,在息屏的时候,开启1个像素的Activity,在屏幕亮的时候,马上关闭,做到用户无感知。下面贴出代码:
mScreenStatusReceiver = new ScreenStatusReceiver(); IntentFilter screenStatus = newIntentFilter(Intent.ACTION_SCREEN_UP); screenStatus.addAction(Intent.ACTION_SCREEN_OFF); registerReceiver(mScreenStatusReceiver, screenStatus); // 友情提示:切记要记得反注册unregist...哦
然后在屏幕广播中写入以下代码:
if(action.equals(Intent.ACTION_SCREEN_OFF)){ // 当屏幕关闭时,启动一个像素的Activity Intent activity = new Intent(context,OnePxActivity.class); activity.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(activity);} else if (action.equals(Intent.ACTION_SCREEN_ON)){ // 用户解锁,关闭Activity // 这里发个广播是什么鬼,其实看下面OnePxAcitivity里面的代码就知道了,发这个广播就是为了finish掉OnePxActivity Intent broadcast = new Intent("FinishActivity"); // broadcast.setFlags(32);Intent.FLAG_INCLUDE_STOPPED_PACKAGES context.sendBroadcast(broadcast);//发送对应的广播}
以上代码中OnePxActivity就是我所说的1像素的Activity,(中国式英语OnePxActivity)
下面贴出Activity的代码:public class OnePxActivity extends Activity { protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { // 收到广播 OnePxActivity.this.finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Window window = getWindow(); // 设置窗口位置在左上角 window.setGravity(Gravity.LEFT | Gravity.TOP); WindowManager.LayoutParams params = window.getAttributes(); params.x = 0; params.y = 0; params.width = 1; params.height = 1; window.setAttributes(params); // 动态注册广播,这个广播是在屏幕亮的时候,发送广播,来关闭当前的Activity registerReceiver(receiver, new IntentFilter("FinishActivity")); } @Override protected void onDestroy() { unregisterReceiver(receiver); Log.e(TAG, TAG + "onDestory"); super.onDestroy(); }}
OnPxActivity在清单文件(AndroidManifest.xml)中的配置
以下是activity的theme(/res/values/styles.xml),具体配置的意思再注释中已经写的很详细。
转: https://blog.csdn.net/cn_1937/article/details/53933073