【问题标题】:How to run the background service in Android O, every minute?如何在 Android O 中每分钟运行一次后台服务?
【发布时间】:2018-09-24 09:22:03
【问题描述】:

我有一个旧应用程序,其中每分钟使用AlarmManagersetExact 调用服务,但在最新的 Android O 中,它不允许我运行服务以同样的方式。我无法使用前台服务,因为我不想在服务运行时显示任何通知。

我希望帮助我调整我的应用程序架构,以使我的代码可以在 Android O 中运行,并且更改最少。

当我在 Android 中运行我的应用程序时,它崩溃了:(。请在下面找到崩溃的堆栈跟踪。

java.lang.RuntimeException: Unable to create application com.***.***.***ControllerApplication: java.lang.IllegalStateException: Not allowed to start service Intent

Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.***.***.qa/com.***.***.services.AlarmService

编辑:

我的应用程序中的任务是时间紧迫的,因此我在AlarmManager 中使用了setExact,但当前支持的API 都没有在准确的时间安排作业。话虽如此,如果我使用 JobScheduler/WorkManager,那么我的应用程序将出现故障。

【问题讨论】:

标签: android service background-service android-jobscheduler android-workmanager


【解决方案1】:

您可以使用每隔 10 分钟调用一次的警报管理器

        AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;

        Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
        notificationIntent.setClass(this,AlarmReceiver_.class);
        notificationIntent.addCategory("android.intent.category.DEFAULT");

        PendingIntent broadcast = PendingIntent.getBroadcast(YourClass.this, r5, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() + 300000L,
                600000L, broadcast);

ManiFest 接收器代码,您将在其中获得接收器响应

<receiver android:name="com.yourpackage.AlarmReceiver_"

        >
        <intent-filter>
            <action android:name="android.media.action.DISPLAY_NOTIFICATION" />
            <category android:name="android.intent.category.DEFAULT" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
            <action android:name="android.intent.action.REBOOT" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />

        </intent-filter>
    </receiver>

您必须创建接收器,您将在其中接收数据作为上述指定名称的 AlarmReceiver_.class

【讨论】:

  • 我已经在使用 AlarmManager 来重复工作,问题是使用 AlarmManager 启动工作在 Android O 中抛出异常。
  • 你能告诉我你是如何调用报警管理器的吗?
  • @SyedTarufNaqvi 您的问题已解决,如果没有,请告诉我。
猜你喜欢
  • 1970-01-01
  • 2019-12-04
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
  • 2020-03-21
  • 2011-01-05
相关资源
最近更新 更多