How to get MIUI Security app auto start permission programmatically?
Asked Answered
V

2

15

I am not getting BOOT_COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile.

My BroadcastReciever is ---

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    // Setting singleAlarm
    SingleAlarmHandler.getInstance().setAlarm(context);

    try {
        // Sending System Setting broadcast
        String offDate = SharedPrefrencesHandler.getInstance(context).readString(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        int type = SystemSettingsType.PHONE_SWITCH_ON_OFF.getNumericType();

        if (offDate == null)
            offDate = "";

        SystemSettingsHandler.getSystemSettingsHandler().makeSystemSettingsCall(context, type, offDate);
        SharedPrefrencesHandler.getInstance(context).removePrefrence(SharedPrefrencesConstants.SWITCH_OFF_DATE);
        } catch (Exception e) {
            Log.e(ChaseForceApplication.TAG, e.getMessage());
        }
    }
}

and manifest:

    <receiver
        android:name=".broadcastlisteners.OnBootReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

with permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

Now I am not getting BOOT COMPLETE broadcast in my Xiaomi Redmi 2 Prime mobile as alarm is not set. But in other android mobiles it is working correctly.

I searched and found that it is problem in MIUI firmware. In such mobile they provide an in built security app and until you allow auto start permission in that Security app, you are unable to get broad cast (any notification).

And as soon as you check that permission in that app you start to get the broadcast.

Now my question is:

How to get MIUI Security app auto start permission( Phones like Redmi) programmatically?

Virg answered 17/8, 2016 at 11:32 Comment(5)
What are you talking about? Show your code. (Manifest, and your receiver)Illiteracy
@Illiteracy , thanks for comment , now i have added my code.. in broadcast receiver if i add only a toast( and remove other code) than still that toast is not displaying in My Redmi Prime 2 mobile but it is displaying in other mobiles like Moto e, Micromax android1 etc....Virg
Hi @ImranKhanSaifi. This is added security feature in MIUI Roms. Any developer who uses Xiaomi phone (with MIUI) will know about this. I was facing the same issue. I searched a lot but it seems MIUI guys did not give any SDK for developer to access permission manager or so. Please reply back if you find any solution for this.Dandrea
Hi @Dandrea , Thanks for reply... Yes u r right. Sequrity app is an System app so we can't have any control on it, User can remove any permission and notification( AutoStart Check) at any time..... One more thing that was creating problem in my app was not getting location when app is not running.. The reason behind it was another setting .. in battery-->Manage apps Battery Usase-> .. It was by default Standard mode is selected that stops your app to get location and using network when your app is not running.. So You also have to check your app in Choose apps option.Virg
Can anyone provide generic solution about what to do to make alarm work properly on different manufactured devices? I am asking for all the solutions on different devices. Thanks.Chancellorsville
S
14

this question already has answer in two Stack Overflow threads:

thread #1 https://mcmap.net/q/37215/-gcm-push-notifications-for-android-devices-are-not-working-on-mi-and-letv-mobiles

String xiaomi = "Xiaomi";
final String CALC_PACKAGE_NAME = "com.miui.securitycenter";
final String CALC_PACKAGE_ACITIVITY = "com.miui.permcenter.autostart.AutoStartManagementActivity";
if (deviceManufacturer.equalsIgnoreCase(xiaomi)) {
    DisplayUtils.showDialog(activity, "Ask for permission", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            try {
                Intent intent = new Intent();
                intent.setComponent(new ComponentName(CALC_PACKAGE_NAME, CALC_PACKAGE_ACITIVITY));
                activity.startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            } catch (Exception e) {
                Logger.e(TAG, "Failed to launch AutoStart Screen ", e);
            }
        }
    }, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    });
}

thread #2 https://mcmap.net/q/37323/-how-to-enable-autostart-option-for-my-app-in-xiaomi-phone-security-app-programmatically-in-android

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 intent = new Intent();
            intent.setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity"));
            startActivity(intent);
        }

and for similar problem on huawei devices:

https://mcmap.net/q/159383/-quot-protected-apps-quot-setting-on-huawei-phones-and-how-to-handle-it

    private void ifHuaweiAlert() {
    final SharedPreferences settings = getSharedPreferences("ProtectedApps", MODE_PRIVATE);
    final String saveIfSkip = "skipProtectedAppsMessage";
    boolean skipMessage = settings.getBoolean(saveIfSkip, false);
    if (!skipMessage) {
        final SharedPreferences.Editor editor = settings.edit();
        Intent intent = new Intent();
        intent.setClassName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity");
        if (isCallable(intent)) {
            final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(this);
            dontShowAgain.setText("Do not show again");
            dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    editor.putBoolean(saveIfSkip, isChecked);
                    editor.apply();
                }
            });

            new AlertDialog.Builder(this)
                    .setIcon(android.R.drawable.ic_dialog_alert)
                    .setTitle("Huawei Protected Apps")
                    .setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", getString(R.string.app_name)))
                    .setView(dontShowAgain)
                    .setPositiveButton("Protected Apps", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            huaweiProtectedApps();
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null)
                    .show();
        } else {
            editor.putBoolean(saveIfSkip, true);
            editor.apply();
        }
    }
}

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
            PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

private void huaweiProtectedApps() {
    try {
        String cmd = "am start -n com.huawei.systemmanager/.optimize.process.ProtectActivity";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            cmd += " --user " + getUserSerial();
        }
        Runtime.getRuntime().exec(cmd);
    } catch (IOException ignored) {
    }
}

private String getUserSerial() {
    //noinspection ResourceType
    Object userManager = getSystemService("user");
    if (null == userManager) return "";

    try {
        Method myUserHandleMethod = android.os.Process.class.getMethod("myUserHandle", (Class<?>[]) null);
        Object myUserHandle = myUserHandleMethod.invoke(android.os.Process.class, (Object[]) null);
        Method getSerialNumberForUser = userManager.getClass().getMethod("getSerialNumberForUser", myUserHandle.getClass());
        Long userSerial = (Long) getSerialNumberForUser.invoke(userManager, myUserHandle);
        if (userSerial != null) {
            return String.valueOf(userSerial);
        } else {
            return "";
        }
    } catch (NoSuchMethodException | IllegalArgumentException | InvocationTargetException | IllegalAccessException ignored) {
    }
    return "";
}
Sublimation answered 30/3, 2017 at 3:51 Comment(3)
Hi @Sublimation , Thanks for reply.. I am using your autostart code for Xiaomi, By your code i am able to reach the autostart setting activity but i am unable to know weather user given auto-start permission Or not. Could i know somehow the action of user, weather user has given permission or not( Status of the permission finally).Virg
as far as I know, you cannot know if user has given permission or not. xiaomi dont provide this feature. the best thing you can do is you can display a small dialog to user with a checklist: "I already allow this app to autostart". and please mark my comment as answer if it help you.Sublimation
@Dika: How if asus device? I using asus and it also blocking autostart and I use autostart manager for allow background serviceEndocrinotherapy
D
1

You need to give permissions in the in build security application for xiaomi.

1. open the security app
2. go to permissions
3. go to auto start
4. enable the applications that you want to keep running in the background!

This worked for me..!

Demott answered 6/2, 2017 at 6:27 Comment(5)
How these steps can be done programatically. You have mentioned manual steps.Subtitle
@VineetKasat are you got any solutions ?Gisarme
@VineetKasat do you got any solutions, how to done these steps are programmattically?Coolidge
@Coolidge These steps cant be done programatically. In our production app we had to float sop steps to be perfromed manually.Subtitle
If what is said is true then isn't it against open competition to give powerful features to popular apps but deny that to others. This means that a new app is at disadvantage. So its a way to stop new apps from outside china to get popular. Rules should be same for everyone big or small.Roughcast

© 2022 - 2024 — McMap. All rights reserved.