我如何以 5 秒的间隔在 android 中执行后台任务? 目前我正在使用警报管理器(setInexactRepeating)但没有成功

Rah*_*hul 1 android alarmmanager background-task

我正在使用警报管理器 (setInexactRepeating),但它会在 1 分钟的间隔后触发事件。我可以将这个间隔设置为 5 秒吗?

    alarmIntent = new Intent(this, AlarmReceiver.class);

    pendingIntent = PendingIntent.getBroadcast(c, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    //Alarm Interval
    int interval = 5000;

    //Firing alarm after an interval of 5 seconds
    manager.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);
Run Code Online (Sandbox Code Playgroud)

Dav*_*idH 6

Handler在你的文件中创建一个私有变量Activity

private Handler mHandler = new Handler();
Run Code Online (Sandbox Code Playgroud)

然后创建一个 Runnable

private Runnable myTask = new Runnable() {
    public void run() {
        doMyThing();
        mHandler.postDelayed(this, 5000); // Running this thread again after 5000 milliseconds        }
};
Run Code Online (Sandbox Code Playgroud)

开始每 5 秒运行一次任务

mHandler.postDelayed(myTask, 0);
Run Code Online (Sandbox Code Playgroud)

然后停止运行任务

mHandler.removeCallbacks(myTask);
Run Code Online (Sandbox Code Playgroud)

这样 myTask 将每 5 秒执行一次,而不必保持循环不断运行。

编辑:

从 API 级别 19 开始,您无法获得重复警报的精确间隔。如果您想使用 AlarmManager,并且您的应用程序的 targetSdkVersion 为 19 或更高,请使用setExact()如下所述的方法。

public void setExact(int 类型,long triggerAtMillis,PendingIntent 操作)

在 API 级别 19 中添加了在指定时间精确发送警报的计划。

此方法类似于 set(int, long, PendingIntent),但不允许操作系统调整传递时间。警报将尽可能接近请求的触发时间。

我认为在 5 秒的时间间隔内无限期地唤醒 CPU 在电池使用方面太昂贵了。

看到这个

注意:从 API 19 (KITKAT) 开始传递警报是不准确的:操作系统将转移警报以最大程度地减少唤醒和电池使用。有新的 API 来支持需要严格交付保证的应用程序;请参阅 setWindow(int, long, long, PendingIntent) 和 setExact(int, long, PendingIntent)。targetSdkVersion 早于 API 19 的应用程序将继续看到以前的行为,其中所有警报都在请求时准确传递。

和这个

注意:从 API 19 开始,所有重复的警报都是不准确的。如果您的应用程序需要精确的交付时间,那么它必须使用一次性精确警报,如上所述重新安排每次。targetSdkVersion 早于 API 19 的旧应用程序将继续将其所有警报(包括重复警报)视为准确。

最后一个引号意味着操作系统将始终更改 API 级别 19 及更高级别的重复警报的间隔。因此,您将无法在较新的平台中准确地获得 5 秒的重复警报。

所以最好的解决方案是在setExact()每次执行代码时使用和重新调度。

或者,如果您想使用具有精确间隔的重复警报,请setRepeating()在设置targetSdkVersion低于 19 时使用,如上面引用的文本。