其他分享
首页 > 其他分享> > 有没有办法在android中持续运行服务?

有没有办法在android中持续运行服务?

作者:互联网

在StackOverFlow上几乎没有类似的问题,但没有一个解决方案适合我

问题

问题是只有少数设备,如OnePlus和MI,一旦用户从最近的应用程序中刷出应用程序,服务就会被杀死.

我读到这些OEM使用一些积极的策略来扼杀服务.我只是想知道是否有任何方法可以保持服务运行或一旦它被杀死就启动它.

我想要的是

我需要运行一个服务,它将在后台持续(24/7)提供位置(此应用程序仅适用于特定的人,所以不用担心电池寿命).

我试过的事情到现在为止:

1)试图运行前台服务.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent)
     } else {
            startService(intent)
     }

也在服务onCreate方法开始通知

@Override
public void onCreate() {
    Log.i("Service", "onCreate");
    startForeground(NOTIFICATION_ID, getnotification());
 }

2)试图在onStartCommand中返回START_STICKY

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {

    initLocationClient();
    initLocationSyncThread();

    return START_STICKY;
}

3)试图在onDestroy和onTaskRemoved中重新启动服务,但它们没有被调用.

4)试图绑定服务

5)我可以安排警报管理器并经常启动服务,但是游戏商店会警告我们的应用程序过于频繁地使用警报管理器并且这是一种不好的做法.现在有使用工作管理员安排不到15分钟的方式,并且仍然不能保证在15分钟后开始.

那么有没有办法继续运行除上述选项之外的服务?

解决方法:

如果你通过THE LINK,你会发现:

Unfortunately, some devices implement killing the app from the recents menu as a force stop. Stock Android does not do this. When an app is force stopped, it cannot execute jobs, receive alarms or broadcasts, etc. So unfortunately, it’s infeasible for us to address it – the problem lies in the OS and there is no workaround.

这是一个众所周知的问题.为了节省电池,许多制造商强制关闭应用程序,从而取消所有期间任务,警报和广播接收器等.主要制造商是OnePlus(您可以选择toogle),Redmi,Vivo,Oppo,Huwaei.

这些设备中的每一个都具有AutoStartManagers / AutoLaunch / StartManager类型的优化管理器.这会阻止后台活动重新开始.您必须手动要求用户将您的应用程序列入白名单,以便该应用程序可以自动启动其后台处理.请点击THISTHIS链接,了解更多信息.

添加到不同制造商的白名单的方法在this stackoverflow answer中给出.即使添加到白名单后,您的应用程序可能因为DOZE模式而无法工作,因为您必须使用ignore battery otimizations

如果您可能想知道,Gmail / Hangout / WhatsApp / Slack / LinkedIn等应用程序已经被这些AutoStart Manager列入白名单.因此,对他们的背景过程没有影响.您总能及时收到更新信息.通知.

标签:android,android-service,background-process,periodic-task
来源: https://codeday.me/bug/20190925/1816180.html