Which is the best method to excecute a task repeatedly in android ? (Eg :- Refreshing scores, Update Ui)
Asked Answered
R

2

7

In android there are some options for refresh handling such as Timer, TimerTask, ScheduledExecutorService, AlarmManager & Handler. Which is the best method to do this.

Did anyone checks the resource utilization of above mentioned methods?. I am listing the implementation of above mentioned methods here.

Using Handler for executing a task repeatedly

final Handler handler = new Handler();
handler.postDelayed(new Runnable() {

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

}, TimeInterval);

Using Timer for executing a task repeatedly

timer = new Timer();

timer.scheduleAtFixedRate(new TimerTask() {

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

}}, 10000, 10000);

Using ScheduledExecutorService for excuting a task repeatedly

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

Using Timer with TimerTask for executing a task repeatedly

Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(),1, TimeInterval);
class UpdateTimeTask extends TimerTask {

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

AlarmManager for executing scheduled task

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 class

public class AlarmReceiver extends BroadcastReceiver { 

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

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

        new MyScheduledTask.execute(param);
    }

}
}

Manifest

<receiver android:name="YourPackageHere.AlarmReceiver"></receiver>
Rhu answered 4/11, 2013 at 8:48 Comment(2)
Instead of checking periodically, you should use services like MQTT to only do things when a new message is available. Facebook uses MQTT too. This, of course, requires server-side configurations.Reproductive
You can try and use push notifications instead of polling. This saves the user a lot of wasted network traffic and battery (most important as you will be preventing the telephone from sleeping all the time and will also be keeping the cellular modem or WiFi antenna up and burning battery all the time). If I remember correctly, the GCM service supports XMPP which is a great protocol to use for chat applications.Fortin
D
1

For being continuously online you'll need an android Service running above a thread. You can use any of the above methods you stated with a service.

BUT as you are making a chat application you'll have to hit the server continuously for every 2-3 seconds, which I think is not good for the user(in terms of internet data that your app will use).

The best recommended protocol to use for a chat application is XMPP(Jabber). It defines all the rules that a normal chat application should have and is very easy to implement. It is a push notification type server which will automatically push a notification to the client whenever a new message has arrived or a new friend is added.(Even Gtalk uses this protocol)

There is a good open source server that provides the XMPP integration named Openfire, which I would recommend.

The same company also provides a library for client side integration named Smack which you can easily implement in your application to use the simple chat functionality.

Direct answered 4/11, 2013 at 9:11 Comment(0)
L
1

Handler is the best method to run you can run it recursively it will be good thinks so ...

If you expect more you should follow MQTT method thats is good in messaging protocol

http://mqtt.org/wiki/doku.php/mqtt_on_the_android_platform

Leija answered 4/11, 2013 at 9:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.