华为手机上的“受保护的应用”设置及其处理方式


134

我有一个用于Android 5.0的Huawei P8,用于测试应用程序。该应用程序需要在后台运行,因为它会跟踪BLE区域。

我发现华为内置了一个称为“受保护的应用程序”的“功能”,可以通过电话设置(电池管理器>受保护的应用程序)进行访问。这样一来,关闭屏幕后,选定的应用程序即可继续运行。

对华为来说明智,但对我来说不幸的是,它看起来像是选择加入的,即默认情况下应用已退出,而您必须手动将其放入。这不是热门产品,因为我可以在常见问题解答中为用户提供建议或打印有关此修复程序的文档,但我最近安装了Tinder(出于研究目的!),并注意到该文件已自动放入受保护列表中。

有谁知道我该如何为我的应用程序做到这一点?清单中是否有设置?这是华为因其受欢迎的应用程序而为Tinder启用的功能吗?


@agamov,不,我找不到更多信息。我只是在Play商店的说明中加入了有关开启受保护的应用的一行。
jaseelder

@TejasPatel,不,我停止尝试解决它,只是在说明中告知用户
jaseelder

Answers:


34
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();
    }

除非有办法知道应用程序是否受到保护,否则,这是最好的办法,但是为了避免每次都显示该应用程序,我会显示“不再显示”,并且消息为“您无法保护”,而操作则是“忽略,我会冒险”或“进入设置”
Saik Caskey

1
华硕自动启动管理器有类似功能吗?
Xan

3
是的,@ Xan。只需按如下所示创建组件名称:ComponentName("com.asus.mobilemanager","com.asus.mobilemanager.autostart.AutoStartActivity"));
Michel Fortes

2
您能解释一下“ sp”对象从哪里来吗?如这里所用?sp.edit().putBoolean("protected",true).commit();因为我知道那是您将价值更改为受保护的权利的地方?
Leonardo G.

2
@LeonardoG。:非常确定“ sp”代表SharedPreferences,最终的SharedPreferences sp = getSharedPreferences(“ ProtectedApps”,Context.MODE_PRIVATE);
papesky '18

76

清单中没有设置,华为已启用Tinder,因为它是一个受欢迎的应用程序。无法知道应用是否受到保护。

反正我以前ifHuaweiAlert()onCreate()显示的AlertDialog

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 "";
}

7
您如何找到类名称“ com.huawei.systemmanager.optimize.process.ProtectActivity”?我想在Sony上为Stamina模式实现类似的功能,但不知道Stamina设置中Stamina的程序包名称和“ except apps”屏幕的类名称。
David Riha

2
如果知道包名和类名,则可以轻松打开屏幕。下面的代码。Intent intent = new Intent(); intent.setComponent(new ComponentName(“ com.huawei.systemmanager”,“ com.huawei.systemmanager.optimize.process.ProtectActivity”));; startActivity(intent);
kinsell '16

1
大卫,最好的选择是logCat。只需移至设置页面并保持logCat打开即可。
天网

1
我可以为我的应用设置功耗密集型吗?
sonnv1368

4
华为P20的正确软件包名称:com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity
rsicarelli

36

对于Pierre的出色解决方案+1,该解决方案适用于多个设备制造商(华为,华硕,oppo ...)。

我想在我的Java Java应用中使用他的代码。我从Pierre和Aiuspaktyn的答案中启发了我的代码。

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.support.v7.widget.AppCompatCheckBox;
import android.widget.CompoundButton;
import java.util.List;

public class Utils {

public static void startPowerSaverIntent(Context context) {
    SharedPreferences settings = context.getSharedPreferences("ProtectedApps", Context.MODE_PRIVATE);
    boolean skipMessage = settings.getBoolean("skipProtectedAppCheck", false);
    if (!skipMessage) {
        final SharedPreferences.Editor editor = settings.edit();
        boolean foundCorrectIntent = false;
        for (Intent intent : Constants.POWERMANAGER_INTENTS) {
            if (isCallable(context, intent)) {
                foundCorrectIntent = true;
                final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(context);
                dontShowAgain.setText("Do not show again");
                dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        editor.putBoolean("skipProtectedAppCheck", isChecked);
                        editor.apply();
                    }
                });

                new AlertDialog.Builder(context)
                        .setTitle(Build.MANUFACTURER + " Protected Apps")
                        .setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", context.getString(R.string.app_name)))
                        .setView(dontShowAgain)
                        .setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                context.startActivity(intent);
                            }
                        })
                        .setNegativeButton(android.R.string.cancel, null)
                        .show();
                break;
            }
        }
        if (!foundCorrectIntent) {
            editor.putBoolean("skipProtectedAppCheck", true);
            editor.apply();
        }
    }
}

private static boolean isCallable(Context context, Intent intent) {
    try {
        if (intent == null || context == null) {
            return false;
        } else {
            List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
                    PackageManager.MATCH_DEFAULT_ONLY);
            return list.size() > 0;
        }
    } catch (Exception ignored) {
        return false;
    }
}
}

}

import android.content.ComponentName;
import android.content.Intent;
import java.util.Arrays;
import java.util.List;

public class Constants {
//updated the POWERMANAGER_INTENTS 26/06/2019
static final List<Intent> POWERMANAGER_INTENTS = Arrays.asList(
        new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
        new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
        new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
        new Intent().setComponent(new ComponentName("com.huawei.systemmanager", Build.VERSION.SDK_INT >= Build.VERSION_CODES.P? "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity": "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerSaverModeActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.oppoguardelf", "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity")),
        new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
        Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")).setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS).setData(Uri.parse("package:"+ MyApplication.getContext().getPackageName())) : null,
        new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
        new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
        new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
        new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
        new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")),
        new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.autostart.AutoStartActivity")),
        new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity"))
                .setData(android.net.Uri.parse("mobilemanager://function/entry/AutoStart")),
        new Intent().setComponent(new ComponentName("com.meizu.safe", "com.meizu.safe.security.SHOW_APPSEC")).addCategory(Intent.CATEGORY_DEFAULT).putExtra("packageName", BuildConfig.APPLICATION_ID)
);
}

在您的计算机中添加以下权限 Android.Manifest

<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>

  • 我仍然遇到OPPO设备的几个问题

我希望这可以帮助别人。


3
效果很好。现在,华为似乎不再使用PretectedApp设置。看起来它正在使用一个名为“启动-管理应用程序启动和后台运行以节省电量”的选项,在该选项中,您必须允许应用程序“自动启动”,“二次启动”和“在后台运行”。知道这是什么意思吗?

我很高兴它为您工作:)。抱歉,我不知道您提到的华为新功能。我应该搜索一下,否则我的应用程序将出现问题。
OussaMah

5
@吨使用此:com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity
西蒙(Simon)

2
将Asus更改为ComponentName(“ com.asus.mobilemanager”,“ com.asus.mobilemanager.autostart.AutoStartActivity”)
Cristian Cardoso

3
在EMUI +5以上更改华为电话:new Intent()。setComponent(new ComponentName(“ com.huawei.systemmanager”,Build.VERSION.SDK_INT> = Build.VERSION_CODES.P?“ com.huawei.systemmanager.startupmgr.ui。 StartupNormalAppListActivity”:“ com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity”))
AlexCuadrón19年

14

适用于所有设备的解决方案(Xamarin.Android)

用法:

MainActivity =>
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    MyUtils.StartPowerSaverIntent(this);
}

public class MyUtils
{
    private const string SKIP_INTENT_CHECK = "skipAppListMessage";

    private static List<Intent> POWERMANAGER_INTENTS = new List<Intent>()
    {
        new Intent().SetComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
        new Intent().SetComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
        new Intent().SetComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
        new Intent().SetComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
        new Intent().SetComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
        new Intent().SetComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
        new Intent().SetComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
        new Intent().SetComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
        new Intent().SetComponent(new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")),
        new Intent().SetComponent(new ComponentName("com.htc.pitroad", "com.htc.pitroad.landingpage.activity.LandingPageActivity")),
        new Intent().SetComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.autostart.AutoStartActivity")),
        new Intent().SetComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")).SetData(Android.Net.Uri.Parse("mobilemanager://function/entry/AutoStart")),
        new Intent().SetComponent(new ComponentName("com.dewav.dwappmanager", "com.dewav.dwappmanager.memory.SmartClearupWhiteList"))
    };

    public static void StartPowerSaverIntent(Context context)
    {
        ISharedPreferences settings = context.GetSharedPreferences("ProtectedApps", FileCreationMode.Private);
        bool skipMessage = settings.GetBoolean(SKIP_INTENT_CHECK, false);
        if (!skipMessage)
        {
            bool HasIntent = false;
            ISharedPreferencesEditor editor = settings.Edit();
            foreach (Intent intent in POWERMANAGER_INTENTS)
            {
                if (context.PackageManager.ResolveActivity(intent, PackageInfoFlags.MatchDefaultOnly) != null)
                {
                    var dontShowAgain = new Android.Support.V7.Widget.AppCompatCheckBox(context);
                    dontShowAgain.Text = "Do not show again";
                    dontShowAgain.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) =>
                    {
                        editor.PutBoolean(SKIP_INTENT_CHECK, e.IsChecked);
                        editor.Apply();
                    };

                    new AlertDialog.Builder(context)
                    .SetIcon(Android.Resource.Drawable.IcDialogAlert)
                    .SetTitle(string.Format("Add {0} to list", context.GetString(Resource.String.app_name)))
                    .SetMessage(string.Format("{0} requires to be enabled/added in the list to function properly.\n", context.GetString(Resource.String.app_name)))
                    .SetView(dontShowAgain)
                    .SetPositiveButton("Go to settings", (o, d) => context.StartActivity(intent))
                    .SetNegativeButton(Android.Resource.String.Cancel, (o, d) => { })
                    .Show();

                    HasIntent = true;

                    break;
                }
            }

            if (!HasIntent)
            {
                editor.PutBoolean(SKIP_INTENT_CHECK, true);
                editor.Apply();
            }
        }
    }
}

在您的计算机中添加以下权限 Android.Manifest

<uses-permission android:name="oppo.permission.OPPO_COMPONENT_SAFE"/>
<uses-permission android:name="com.huawei.permission.external_app_settings.USE_COMPONENT"/>

为了帮助找到此处未列出的设备的活动,只需使用以下方法来帮助找到正确的活动以供用户打开

C#

public static void LogDeviceBrandActivities(Context context)
{
    var Brand = Android.OS.Build.Brand?.ToLower()?.Trim() ?? "";
    var Manufacturer = Android.OS.Build.Manufacturer?.ToLower()?.Trim() ?? "";

    var apps = context.PackageManager.GetInstalledPackages(PackageInfoFlags.Activities);

    foreach (PackageInfo pi in apps.OrderBy(n => n.PackageName))
    {
        if (pi.PackageName.ToLower().Contains(Brand) || pi.PackageName.ToLower().Contains(Manufacturer))
        {
            var print = false;
            var activityInfo = "";

            if (pi.Activities != null)
            {
                foreach (var activity in pi.Activities.OrderBy(n => n.Name))
                {
                    if (activity.Name.ToLower().Contains(Brand) || activity.Name.ToLower().Contains(Manufacturer))
                    {
                        activityInfo += "  Activity: " + activity.Name + (string.IsNullOrEmpty(activity.Permission) ? "" : " - Permission: " + activity.Permission) + "\n";
                        print = true;
                    }
                }
            }

            if (print)
            {
                Android.Util.Log.Error("brand.activities", "PackageName: " + pi.PackageName);
                Android.Util.Log.Warn("brand.activities", activityInfo);
            }
        }
    }
}

爪哇

public static void logDeviceBrandActivities(Context context) {
    String brand = Build.BRAND.toLowerCase();
    String manufacturer = Build.MANUFACTURER.toLowerCase();

    List<PackageInfo> apps = context.getPackageManager().getInstalledPackages(PackageManager.GET_ACTIVITIES);

    Collections.sort(apps, (a, b) -> a.packageName.compareTo(b.packageName));
    for (PackageInfo pi : apps) {
        if (pi.packageName.toLowerCase().contains(brand) || pi.packageName.toLowerCase().contains(manufacturer)) {
            boolean print = false;
            StringBuilder activityInfo = new StringBuilder();

            if (pi.activities != null && pi.activities.length > 0) {
                List<ActivityInfo> activities = Arrays.asList(pi.activities);

                Collections.sort(activities, (a, b) -> a.name.compareTo(b.name));
                for (ActivityInfo ai : activities) {
                    if (ai.name.toLowerCase().contains(brand) || ai.name.toLowerCase().contains(manufacturer)) {
                        activityInfo.append("  Activity: ").append(ai.name)
                                .append(ai.permission == null || ai.permission.length() == 0 ? "" : " - Permission: " + ai.permission)
                                .append("\n");
                        print = true;
                    }
                }
            }

            if (print) {
                Log.e("brand.activities", "PackageName: " + pi.packageName);
                Log.w("brand.activities", activityInfo.toString());
            }
        }
    }
}

执行启动和搜索通过日志文件,添加一个logcat的过滤器TAGbrand.activities

MainActivity =>
protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);

    MyUtils.LogDeviceBrandActivities(this);
}

样本输出:

E/brand.activities: PackageName: com.samsung.android.lool
W/brand.activities: ...
W/brand.activities:   Activity: com.samsung.android.sm.ui.battery.AppSleepSettingActivity
W/brand.activities:   Activity: com.samsung.android.sm.ui.battery.BatteryActivity <-- This is the one...
W/brand.activities:   Activity: com.samsung.android.sm.ui.battery.BatteryActivityForCard
W/brand.activities: ...

因此,组件名称为:

new ComponentName("<PackageName>", "<Activity>")
new ComponentName("com.samsung.android.lool", "com.samsung.android.sm.ui.battery.BatteryActivity")

如果活动旁边有权限,则Android.Manifest打开时需要输入以下内容:

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

在此答案中注释或编辑新组件。所有帮助我将不胜感激。


您如何找到类名称“ com.huawei.systemmanager.optimize.process.ProtectActivity”?我想为Qmobile实现类似的功能,但不知道Qmobile的软件包名称和“ except apps”屏幕的类名称
Noaman Akram

1
您可以在有关Qmobile的答案中进行编辑.. new Intent()。setComponent(new ComponentName(“ com.dewav.dwappmanager,” com.dewav.dwappmanager.memory.SmartClearupWhiteList“)),
Noaman Akram,

我已使用此代码,但无法在Samsung J6 mobile中使用。
Shailesh

@Pierre您是否考虑过将其放入GitHub上的库中,以便其他项目可以直接包含它?然后其他开发人员也可以通过请求请求贡献新组件。有什么想法吗?
Shankari

1

我正在使用@Aiuspaktyn解决方案,该解决方案缺少在用户将应用程序设置为受保护后如何检测何时停止显示对话框的部分。我正在使用服务来检查应用程序是否已终止,并检查其是否存在。


3
您可以发布服务样本吗?
扎基

0

您可以使用此库将用户导航到受保护的应用程序或自动启动:

自动启动器

如果电话支持自动启动功能,则可以向用户显示提示以在这些应用中启用您的应用

您可以通过以下方法进行检查:

AutoStartPermissionHelper.getInstance().isAutoStartPermissionAvailable(context)

为了将用户导航到该页面,只需调用以下命令:

AutoStartPermissionHelper.getInstance().getAutoStartPermission(context)

-4

PowerMaster->自动启动->在阻止的部分中找到您的应用并允许

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.