在安卓中,执行重复任务的最佳方法是什么?(例如:刷新分数,更新UI)

7
在Android中有一些处理刷新的选项,比如定时器(Timer)、定时任务(TimerTask)、ScheduledExecutorService、AlarmManager和Handler。哪种方法最好呢?
有人检查过上述方法的资源利用率吗?我在这里列出了上述方法的实现。
使用Handler重复执行任务。
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {

    public void run() {
        new MyScheduledTask.execute(param);
    }

}, TimeInterval);

使用计时器重复执行任务

timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

    synchronized public void run() {
        new MyScheduledTask.execute(param);
        }

}}, 10000, 10000);

使用ScheduledExecutorService重复执行任务

ScheduledExecutorService scheduler =
Executors.newSingleThreadScheduledExecutor();
scheduler.scheduleAtFixedRate
  (new Runnable() {
     public void run() {
        new MyScheduledTask.execute(param);
     }
  }, 0, 10, TimeInterval);

使用Timer和TimerTask重复执行任务
在IT技术中,我们常常需要定期或定时地执行某项任务。为了实现这一目的,Java提供了一个方便的工具——Timer和TimerTask。
Timer是一个用于调度任务的类,可以安排在指定时间执行某项操作。它通常与TimerTask配合使用,TimerTask则表示要执行的具体任务。
通过Timer和TimerTask,我们可以轻松地实现对某个任务的重复执行。例如,我们可以设置每隔一段时间执行一次某项操作,或者每天、每周等固定时间点执行一次某项操作。
总之,使用Timer和TimerTask可以让我们更加方便地进行任务调度,提高工作效率。
Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
class UpdateTimeTask extends TimerTask {

    public void run() 
       {        
        new MyScheduledTask.execute(param);
       }
}

AlarmManager用于执行预定任务

public void setupTask(){

    // check task is scheduled or not
    boolean alarmUp = (PendingIntent.getBroadcast(this, 0, 
            new Intent("YourPackageHere.AlarmReceiver"), 
            PendingIntent.FLAG_NO_CREATE) != null);

    if (  !alarmUp) {
        Intent intent = new Intent("YourPackageHere.AlarmReceiver");
        intent.putExtra("activate", true);
        PendingIntent pendingIntent =
                    PendingIntent.getBroadcast(this, 0, 
                  intent, PendingIntent.FLAG_UPDATE_CURRENT);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 0);   
        calendar.set(Calendar.MINUTE, 1);
        calendar.set(Calendar.SECOND, 0);

        AlarmManager alarmManager =
                    (AlarmManager)
                    this.getSystemService(this.ALARM_SERVICE);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY,
                    pendingIntent);

        calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 7);   
        calendar.set(Calendar.MINUTE, 0);

        alarmManager = (AlarmManager)
                    this.getSystemService(this.ALARM_SERVICE);
        PendingIntent pendingIntent2 =
                    PendingIntent.getBroadcast(this, 1, 
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    calendar.getTimeInMillis(),
                    AlarmManager.INTERVAL_DAY, pendingIntent2);         

    }

}

AlarmManager类

public class AlarmReceiver extends BroadcastReceiver { 

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

    if (intent.hasExtra("activate")) {

        new MyScheduledTask.execute(param);
    }

}
}

清单

<receiver android:name="YourPackageHere.AlarmReceiver"></receiver>

1
不要定期检查,应该使用像MQTT这样的服务,只有在有新消息可用时才执行操作。Facebook也使用MQTT。当然,这需要服务器端配置。 - Lawrence Choy
你可以尝试使用推送通知来代替轮询。这样可以节省用户大量的网络流量和电池(最重要的是,你将防止手机一直保持唤醒状态,并且还将一直保持蜂窝调制解调器或WiFi天线处于开启状态并消耗电池)。如果我没记错的话,GCM服务支持XMPP协议,这是一个非常适合聊天应用程序使用的协议。 - lucian.pantelimon
2个回答

1

要保持持续在线状态,您需要运行在线程之上的一个android Service。您可以使用您所述的任何方法与服务一起使用。

但是,由于您正在开发聊天应用程序,您将不断地每2-3秒钟向服务器发送请求,我认为这对用户来说并不好(就您的应用程序将使用的互联网数据而言)。

为聊天应用程序推荐使用的最佳协议是 XMPP(Jabber)。它定义了所有正常聊天应用程序应该具有的规则,并且非常易于实现。它是一种推送通知类型的服务器,当新消息到达或添加新朋友时,它会自动向客户端推送通知。(即使Gtalk也使用此协议)

有一个很好的开源服务器提供了XMPP集成,名为Openfire,我建议您使用它。

同一家公司还提供了一个客户端集成库,名为Smack,您可以轻松地在应用程序中实现使用简单的聊天功能。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接