小米和Oppo限制后台服务 [英] Background Services are restricted in Xiaomi and Oppo

查看:307
本文介绍了小米和Oppo限制后台服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在开发在前台服务中运行MQTT的应用程序. 问题出在小米Redmi Note 7上,该服务在我们终止该应用程序后被终止,但在其他品牌上则正常.我没有在Oppo和Vivo上测试该应用程序,但是当我搜索它们时也遇到了问题. 在服务的onCreate方法中,我调用了startForeground(NOTIFICATION_ID, notification),清单中的服务声明就是这样

We are developing an app With MQTT running in a foreground service. The problem is on Xiaomi Redmi Note 7, the service gets killed after we kill the app but on other brands It works fine. I did not test the app on Oppo and Vivo but as I searched they have problem too. In onCreate method of the service, I called startForeground(NOTIFICATION_ID, notification) and my service declaration in manifest is like this

<service
    android:name=".service.mqtt.MqttService"
    android:enabled="true"
    android:exported="false"
    android:foregroundServiceType="location" />

我也将foregroundServiceType更改为connectedDevice|dataSync|mediaPlayback,并添加了android:stopWithTask="false"并以onStartCommand的服务方法返回了START_STICKY,但仍然无法正常工作.

I've also changed foregroundServiceType to connectedDevice|dataSync|mediaPlayback and added android:stopWithTask="false" and returned START_STICKY in onStartCommand method of service but still not working.

推荐答案

最后,我找到了答案

Finally I've found the answer here

private static final Intent[] POWERMANAGER_INTENTS = {
    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.startupmgr.ui.StartupNormalAppListActivity")),
    new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
    new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.appcontrol.activity.StartupAppControlActivity")),
    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.MainActivity"))
};



for (Intent intent : POWERMANAGER_INTENTS)
    if (getPackageManager().resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY) != null) {
            // show dialog to ask user action
        break;
}

修改: 另外,检查用户是否启用了自动启动也存在问题. 在我搜索时,目前没有可用的解决方案.所以我自己设计了一个解决方案. 我创建了一个工作程序,它将每25分钟节省一次系统时间. 每次打开该应用程序时,我都会检查首选项,如果从节省的时间开始超过30分钟,则意味着该工作人员无法完成工作,因此用户上次可能没有启用自动启动功能,因此必须再次提示.

edit: Also there is a problem checking if the user enabled auto-start or not. As I searched, currently there are no solutions available. So I designed a solution myself. I created a worker which will save system's time in preferences every 25 min. Every time the app is opened, I check the preferences, and if it is more than 30 min passed from the saved time, It means that worker could not do the work, so possibly user did not enable auto-start the last time and must prompt again.

class BackgroundCheckWorker(val appContext: Context, val workerParams: WorkerParameters) :
Worker(appContext, workerParams), KoinComponent {


override fun doWork(): Result {
    val pref = appContext.getSharedPreferences(PermissionHandler.AUTO_START_PREF, Context.MODE_PRIVATE)
    val editor = pref.edit()
    editor.putString(AUTO_START_PREF_KEY, Calendar.getInstance().time.toString())
    editor.apply()
    return Result.success()
}
}

在启动时,我调用此函数:

And in splash I call this function:

fun requestUnrestrictedBackgroundService(context: Activity): Boolean {
            val pref = context.getSharedPreferences(AUTO_START_PREF, Context.MODE_PRIVATE)
            var updated = false
            val lastUpdate = pref.getString(AUTO_START_PREF_KEY, "")
            updated = if (lastUpdate == null || lastUpdate == "") {
                val editor = pref.edit()
                editor.putString(AUTO_START_PREF_KEY, Calendar.getInstance().time.toString())
                editor.apply()
                false
            } else lastUpdate != "" &&
                    DateUtil.minAgo(lastUpdate) <= 30
            if (!updated) {
                for (intent in POWERMANAGER_INTENTS)
                    if (context.packageManager.resolveActivity(
                            intent,
                            PackageManager.MATCH_DEFAULT_ONLY
                        ) != null
                    ) {
                            val dialog = AlertDialog.Builder(context)
                            dialog.setMessage("On this device you must allow us to run services in background")
                                .setPositiveButton("Yes") { paramDialogInterface, paramInt ->
                                    val editor = pref.edit()
                                    editor.putString(AUTO_START_PREF_KEY, Calendar.getInstance().time.toString())
                                    editor.apply()
                                    context.startActivityForResult(intent, 1234)
                                }
                                .setNegativeButton("Cancel") { paramDialogInterface, paramInt -> context.finish() }
                            dialog.show()
                            return false
                    }
            }
            return true
        }

这篇关于小米和Oppo限制后台服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆