I was able to receive Screen state when the app is running, but when the app is stop I can't receive it.
here my code LockService
public class LockService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
Log.e("Action","Screen");
final BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
Log.e("Sample","Screen");
return super.onStartCommand(intent, flags, startId);
}
public class LocalBinder extends Binder {
LockService getService() {
return LockService.this;
}
}
}
BroadcastReceiver
public class ScreenReceiver extends BroadcastReceiver {
Intent intent;
@Override
public void onReceive(final Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.e("Screen state"," ON");
Intent i = new Intent(context, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
MainActivity in the onCreate activity
startService(new Intent(getApplicationContext(), LockService.class));
Manifest.xml
<service android:name=".LockService">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</service>
I want to start an Activity when user wake the phone
My code works. Just my phone unstable, I reformat my phone then my app works perfectly. Thanks for devote.
phone:Xiaomi Mi 5 OS:Android 6.0