Posted on

Restart service if start_sticky on Xiaomi

Service does not restart after a user kill a application on Xiaomi devices even we use

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

Xiaomi devices have extra permissions called “auto start” that allows services be restarted automatically after they were killed.

I did not find how to check autostart permissions programmatically.

But we can redirect a user to permission screen by this code

String manufacturer = "xiaomi";
if (manufacturer.equalsIgnoreCase(android.os.Build.MANUFACTURER)) {
    //this will open auto start screen where user can enable permission for your app
    Intent intent1 = new Intent();
    intent1.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
    startActivity(intent1);
}

Also for Huawei:

if("huawei".equalsIgnoreCase(android.os.Build.MANUFACTURER) && !sp.getBoolean("protected",false)) {
        AlertDialog.Builder builder  = new AlertDialog.Builder(this);
        builder.setTitle(R.string.huawei_headline).setMessage(R.string.huawei_text)
                .setPositiveButton(R.string.go_to_protected, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent();
                        intent.setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity"));
                        startActivity(intent);
                        sp.edit().putBoolean("protected",true).commit();
                    }
                }).create().show();
    }

Links:

https://stackoverflow.com/questions/41627537/service-not-start-again-after-kill-app-even-use-start-sticky-in-some-device

https://stackoverflow.com/questions/42996646/how-to-enable-autostart-for-my-app-in-xiaomi-devices

http://en.miui.com/thread-410707-1-1.html

To open app settings screen

Intent intent = new Intent();
intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package", getPackageName(), null);
intent.setData(uri);
startActivity(intent);
Leave a Reply

Your email address will not be published. Required fields are marked *

 

This site uses Akismet to reduce spam. Learn how your comment data is processed.