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());
}}