AsyncTasks
are meant to be used for relatively short operations, so if you're looking to do some long polling, you should probably try a different approach. If you want to periodically make a network call, you could have a Service
running in the background.
The following code might help you. It's just a template of a Service that gets executed every 10 seconds. Remember that the network call needs to be done off the UI thread:
public class MyService extends Service {
private IBinder mBinder = new SocketServerBinder();
private Timer mTimer;
private boolean mRunning = false;
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if (mRunning) {
// make your network call here
}
}
}, 10000, 10000);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mRunning = true;
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
mRunning = true;
return mBinder;
}
@Override
public boolean onUnbind(Intent intent) {
mRunning = false;
return super.onUnbind(intent);
}
public class SocketServerBinder extends Binder {
public MyService getService() {
return MyService.this;
}
}
}
manpreet Best Answer 2 years ago
I have some easy question.
Can I make long polling on java, using only AsyncTask?
when responce return TIME OUT, how i make request again?
Best regards. sorry for my bad english