我正在构建一个应该接收Android android.intent.action.SCREEN_ON
广播的应用,并在后台执行某些操作。
(该广播受到保护,无法添加到Manifest中的IntentFilter部分,需要通过registerReceiver()
以编程方式注册)
我知道如何启动服务。我知道如何让它独立于启动它的Activity(所以它不会因此而死)。真正的问题是:
如何在服务中注册SCREEN_ON广播接收器,即使系统发送广播时由于RAM较低导致服务暂时被设备杀死,服务也会接收到它?
答案 0 :(得分:1)
public class OnBootService extends Service {
private static final String TAG = OnBootService.class.getSimpleName();
private PowerButtonReceiver mPowerButtonReceiver = null;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
if (mPowerButtonReceiver==null) {
mPowerButtonReceiver = new PowerButtonReceiver();
registerReceiver(mPowerButtonReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
}
return Service.START_NOT_STICKY;
}
@Override
public void onCreate() {
super.onCreate();
Log.i(TAG,"onCreate()");
}
// unregister the Receiver when the Service gets stopped (destroyed)
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mPowerButtonReceiver);
Log.i(TAG, ""+TAG+" stopped: "+ new Date().toString());
}
}
编辑:我也添加了powerButtonReceiver:
public class PowerButtonReceiver extends BroadcastReceiver {
private static final String TAG = "PowerButtonReceiver";
private int mPowerClickCounter = 0;
private boolean inTime = true;
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPref = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
Boolean bCheck = sharedPref.getBoolean("PowerButtonReceiverState", false);
// check if screen is on
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
Boolean screenOn = pm.isScreenOn();
Log.i(TAG, "Screen is on: " + screenOn.toString());
}}