First, I've tried create a receiver to receive screen on/off and register receiver on AndroidManifest.xml like below, but unfortunately it does not work.
ScreenReceiver.javapackage com.prhythm.training.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by Bruce on 7/15/2014. */ public class ScreenReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.d("Receiver", String.format("Broadcast action: %s", intent.getAction())); } }AndroidManifest.xml
<receiver android:name=".service.ScreenReceiver"> <intent-filter> <action android:name="android.intent.action.SCREEN_ON"/> <action android:name="android.intent.action.SCREEN_OFF"/> </intent-filter> </receiver>
I's nessary to register screen action receiver by code, so I've change the as
ScreenReceiver.javapackage com.prhythm.training.service; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by Bruce on 7/15/2014. */ public class ScreenReceiver extends BroadcastReceiver { public static ScreenReceiver CURRENT; @Override public void onReceive(Context context, Intent intent) { Log.d("Receiver", String.format("Broadcast action: %s", intent.getAction())); } }ScreenService.java
package com.prhythm.training.service; import android.app.Service; import android.content.Intent; import android.content.IntentFilter; import android.os.IBinder; /** * Created by Bruce on 7/15/2014. */ public class ScreenService extends Service { @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { // Register screen on/off receiver if (ScreenReceiver.CURRENT == null) ScreenReceiver.CURRENT = new ScreenReceiver(); getApplicationContext().registerReceiver(ScreenReceiver.CURRENT, new IntentFilter(Intent.ACTION_SCREEN_ON)); getApplicationContext().registerReceiver(ScreenReceiver.CURRENT, new IntentFilter(Intent.ACTION_SCREEN_OFF)); } }
Then, start this service is required
startService(new Intent(this, ScreenService.class));