BroadcastReceiver for Screen On/Off in ANDROID When App is not running

核能气质少年 提交于 2019-12-04 22:45:11

If you want it to run in the background even if the app is not running, you will have to create a Service. In the Service class you will have to register to your Receiver.

public class ScreenOnOffService extends Service {

    private ScreenOnOffReceiver mScreenReceiver;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        registerScreenStatusReceiver();
    }

    @Override
    public void onDestroy() {
        unregisterScreenStatusReceiver();
    }

    private void registerScreenStatusReceiver() {
        mScreenReceiver = new ScreenOnOffReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenReceiver, filter);
    }

    private void unregisterScreenStatusReceiver() {
        try {
            if (mScreenReceiver != null) {
                unregisterReceiver(mScreenReceiver);
            }
        } catch (IllegalArgumentException e) {}
    }
}

After creating the service class don't forget to add your service to the Manifest:

<service android:name="com.myapp.services.ScreenOnOffService" />

Then to start the service you can write this in your main activity:

Intent intent = new Intent(this, ScreenOnOffService.class);
startService(intent);

For the broadcast class:

public class ScreenOnOffReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            Log.d("StackOverflow", "Screen Off");

        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            Log.d("StackOverflow", "Screen On");
        }
    }
}

Note: for me the screen off and screen on ,did NOT work inside the manifest , but only at runtime.

A bit late for the party but might help someone. Do as mentioned by @CookieMonster above, further while starting your service ScreenOnOffService , do like this

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(new Intent(this, ScreenOnOffService.class));
    } else {
        startService(new Intent(this, ScreenOnOffService.class));
    }

and in your ScreenOnOffService onCreate() method paste the below code

if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "your_channel_id";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "Notification Channel Title",
                NotificationManager.IMPORTANCE_DEFAULT);

        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);

        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();

        startForeground(1, notification);
    }

now run your application. It will work as expected.

Broad cast reciever can run when app is not running only if you add permission wake.lock in your manifest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!