現在手機用戶鎖屏後應用很快會被手機管家殺掉進程,爲了保證項目中的service一直存活,所以在用戶進行鎖屏時需要創建一個透明的Activity保證程序一直運行不被手機管家回收掉
1、自定義廣播接收者接收手機開關機這個廣播事件
package com.liveon;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { //屏幕關閉
Log.i("song","鎖屏");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { //屏幕打開
Log.i("song","開屏");
}
}
}
2、在需要的MainActivity中動態註冊廣播
private void registerService() {
ScreenReceiver screenBroadcastReceiver = new ScreenReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_USER_PRESENT);
getApplicationContext().registerReceiver(screenBroadcastReceiver, filter);
}
3、運行項目,在監測到用戶鎖屏時啓動一個1像素的透明的Activity就可以,用戶解鎖時,把這個透明的activity給finish就可以了