1

我正在构建一个应用程序,它应该接收 Android 的android.intent.action.SCREEN_ON广播并在后台做一些事情。

(该广播受保护,不能添加到 Manifest 中的 IntentFilter 部分,需要通过 以编程方式注册registerReceiver()

我知道如何启动服务。我知道如何使它独立于启动它的 Activity(所以它不会随它而死)。真正的问题是:

如何在 Service 中注册 SCREEN_ON 广播接收器,以便在系统发送广播时,即使由于 RAM 不足而导致 Service 被设备临时杀死,Service 也能接收到它?

4

1 回答 1

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());
 }}      
于 2013-10-17T09:32:46.840 回答