Running a foreground service in Chinese ROMs

1.5k views Asked by At

I've made a foreground service to constantly scan for BLE devices around me. For some reason it seems to work flawlessly on my stock android device Google pixel and also on Samsung S9+.

But recently I tested the app with a Chinese ROM(Oneplus 6T, Xiaomi Poco F1) the foreground service seems to be killed there after a few minutes. I've used workmanager to restart service but the app is not restarting and I get a bug report instead for the app.

Also on Chinese ROM devices below android 8.0(Xiaomi redmi 3s prime), simple service wont work, I need to use a foreground service there as well. Is there any solution to solving this?

2

There are 2 answers

12
Dewey Reed On

Ask users to whitelist your app. This is the only solution. Even foreground service + wake lock won't work.

There was a discussion last month: Workmanager reliability for periodic tasks on Chinese roms (Xiaomi, Huawei, and so on). There are some useful links in there but eventually you'll have to let users whitelist your app in every ROM's specific battery optimization(or other name) settings.

1
Vikash Bijarniya On

A simple approach would be to ask user to put your app in non-optimized apps by opening the battery optimization settings at the starting of your app Use below code to open the setting:

    Intent batterySaverIntent=new Intent(Settings.ACTION_BATTERY_SAVER_SETTINGS);
startActivity(batterySaverIntent);

Or you can try this:

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        startForegroundService(new Intent(this, ServiceClass.class));
    }