如何在每个午夜运行的android上设置任务?

时间:2016-05-25 12:26:36

标签: java android

我需要在android上设置任务,检查新数据并从远程服务器下载。 基本上我知道如何运行任务,但问题是: 我应该从主thred运行scheduleAlarm()方法吗? 这意味着每次用户打开应用程序时都会调用此方法。 它会创建重复的任务吗? 设置此类任务的正确方法是什么?

int na = numbers[a] - '0';
int nb = numbers[b] - '0';
int nc = numbers[c] - '0';
int nd = numbers[d] - '0';

z = na * nb * nc * nd;

2 个答案:

答案 0 :(得分:1)

使用PendingIntent启动执行网络请求的服务。

PendingIntent.getService(...)

但请确保它在执行异步时以及IntentService或实际网络请求。

编辑:抱歉,我误解了这个问题。 PendingIntent中的最后一个参数指定PendingIntent已存在时要执行的操作。在示例中,您告诉如果这样的PendingIntent已经存在,那么应该更新它。因此,只要PendingIntent的参数保持不变,你就应该没问题,因为没有创建新的PendingIntent。

答案 1 :(得分:1)

https://developer.android.com/training/scheduling/alarms.html

根据文档alarmManager.set将取消您的待处理事件并安排新事件,这意味着每个事件将调用onReceive。

如果您想管理任务,请在AlarmReciever

中保持激烈

公共类AlarmReciever扩展了BroadcastReceiver {

ConnectivityManager cm = null;
NetworkInfo netInfo = null;
Task task;
@Override
public void onReceive(Context context, Intent intent)
{
 // reschedule alarm

 // check if not null and not finished return or cancel old one and create new 'task'



}

}