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());
}}
這是你在找什麼? – bofredo
看起來這應該這樣做,但是如果服務正在重新啓動什麼(例如,由於內存不足)時的廣播系統發送的?將'PowerButtonReceiver'的'的onReceive()'被稱爲靜止? –
,直到你重新啓動設備或明確地停止它的服務應該是積極的。第二種選擇:您可以使服務變得粘稠,然後只有在您明確停止服務時纔會停止。 – bofredo