【问题标题】:how to run app in background on devices that kill background services (like Xiomi)?如何在杀死后台服务的设备(如小米)上在后台运行应用程序?
【发布时间】:2017-09-12 13:50:24
【问题描述】:

我尝试在后台运行服务。已使用 Start_Sticky。 基本上这个answer。它在许多设备上都可以正常工作,但在小米联想等某些设备中,当应用程序从“最近的应用程序”屏幕中删除时,该服务就会消失。我也尝试过为特定应用程序和整个系统停用节电程序,但这也不起作用。

如何让它在这些设备上工作?我知道这是可能的,因为即使应用程序不在“最近的应用程序”屏幕中,某些应用程序(如 whatsapp)和游戏也能够发送通知。

【问题讨论】:

    标签: android service


    【解决方案1】:

    您可以在服务类的 onTaskRemoved() 方法中用 1 分钟创建警报。 1分钟后会自动调用并重启服务。

    在服务类中

    public void onTaskRemoved(Intent rootIntent) {
         Intent restartService = new Intent(getApplicationContext(), YourService.class);
         restartService.setPackage(Yourpackagename);
         PendingIntent restartServiceIntent = PendingIntent.getService(getApplicationContext(), 1, restartService, PendingIntent.FLAG_ONE_SHOT);
         AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
         alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealTime()+1000, restartServiceIntent);
    }
    

    【讨论】:

    • onTaskRemoved() 如果您在最近的应用程序中单击“全部清除”,则不起作用。
    • 如果是这种情况,请每 10 分钟设置一次重复警报。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-08
    • 2021-12-11
    相关资源
    最近更新 更多