【问题标题】:Android KitKat 4.4 kills my Service stared by Alarm ManagerAndroid KitKat 4.4 杀死了我被警报管理器盯着的服务
【发布时间】:2014-01-22 02:52:21
【问题描述】:

我对 Android KitKat 和 Alarm Manager 有一个大问题。

我所有的应用程序都使用始终在后台运行的服务,而不会被 Android 杀死。

在 Android 4.4 KitKat 之前,我发现的解决方案是通过 AlarmManager 触发的 BroadcastReceiver 启动服务。

...

Intent intent = new Intent(c, MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        AlarmManager am = (AlarmManager) c.getSystemService(Context.ALARM_SERVICE);

        if (Build.VERSION.SDK_INT<Build.VERSION_CODES.KITKAT) {
            am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent);
        } else {
            setAlarmFromKitkat(am, System.currentTimeMillis(), pendingIntent);
        }
...




@TargetApi(19)
    private static void setAlarmFromKitkat(AlarmManager am, long ms, PendingIntent pi){
        am.setExact(AlarmManager.RTC_WAKEUP, ms, pi);
    }

...


public class MyReceiver extends BroadcastReceiver {

     @Override
     public void onReceive(Context context, Intent intent) {

            Intent service = new Intent(context, MyService.class);
            context.startService(service);
     }

}

通过这个解决方案在 Android 4.4 KitKat 上我可以启动服务,但一段时间后 Android 会杀死它!

有没有办法让服务在后台运行而不会被 Android 4.4 KitKat 杀死?

非常感谢

【问题讨论】:

标签: android service alarmmanager android-4.4-kitkat kill-process


【解决方案1】:

适用于 Android Kitkat 版本

如果您的应用使用 AlarmManager...

当您将应用的 targetSdkVersion 设置为“19”或更高时,您使用 set() 或 setRepeating() 创建的警报将不准确。

为了提高电源效率,Android 现在将来自所有应用程序在相当相似的时间发生的警报汇总在一起,以便系统唤醒设备一次而不是多次来处理每个警报。

如果您的闹钟与确切的时钟时间无关,但在特定时间范围(例如下午 2 点到 4 点之间)调用闹钟仍然很重要,那么您可以使用新的 setWindow() 方法,该方法接受警报的“最早”时间和系统应该调用警报的最早时间之后的时间“窗口”。

如果您的闹钟必须固定到准确的时钟时间(例如日历事件提醒),那么您可以使用新的 setExact() 方法。

这种不精确的批处理行为仅适用于更新后的应用。如果您将 targetSdkVersion 设置为“18”或更低,则在 Android 4.4 上运行时,您的警报将继续像以前版本一样运行。

原始来源: http://developer.android.com/about/versions/android-4.4.html

【讨论】:

  • 所以没有办法让我的服务在没有 Android KitKat 的情况下运行。对吗?
  • 也许我来晚了,你为什么不使用START STICKY?还可以使用 traceview 优化您的服务。
【解决方案2】:

在kitkat中,使用下面的代码sn-p自动重启te服务:

@Override
public void onTaskRemoved(Intent rootIntent) {
    // TODO Auto-generated method stub
    Intent restartService = new Intent(getApplicationContext(),
            this.getClass());
    restartService.setPackage(getPackageName());
    PendingIntent restartServicePI = 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, restartServicePI);

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-16
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多