gpt4 book ai didi

android - 如何设置即使应用程序停止也会继续运行的定时事件

转载 作者:行者123 更新时间:2023-11-29 18:20:05 25 4
gpt4 key购买 nike

每当最终用户单击“提交”按钮时,我都需要运行一个进程。应用程序需要每 X 分钟 Y 次尝试处理屏幕上的数据,即使应用程序已关闭。因此,它将需要尝试进行一些处理,直到发生以下情况之一:1)提交的数据处理成功2)处理重试了Y次,仍然没有成功3) 应用程序被操作系统终止或手机关机。

如果最终用户的手机仍然开机但应用程序已停止,用于完成此操作的正确界面是什么?

如果我使用 Handler/Runnable,那只会在应用程序保持 Activity 状态时起作用。AlarmManager 看起来像是在您希望处理在特定时间运行时使用的。

任何建议将不胜感激!

最佳答案

我用这个方法来设置闹钟。

private void setAlarm(){
Context context = getApplicationContext();
AlarmManager mgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, OnAlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);

myCal = Calendar.getInstance();
myCal.setTimeInMillis(myPrefs.getLong("time", 0));

mgr.set(AlarmManager.RTC_WAKEUP, myCal.getTimeInMillis(), pi);
Log.i(myTag, "alarm set for " + myCal.getTime().toLocaleString());
Toast.makeText(getApplicationContext(),"Alarm set for " + myCal.getTime().toLocaleString(), Toast.LENGTH_LONG).show();

}

在我的 onAlarmReciever onRecieve 方法中是这样的:

        Intent i = new Intent(context, AlarmActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

所以基本上,当 Intent 触发时,它会启动 AlarmActivity。在该 Activity 中,您可以让它尝试您正在做的事情,如果失败,请再次调用 setAlarm()

关于android - 如何设置即使应用程序停止也会继续运行的定时事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5984756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com