Start AsyncTask in TimerTask - android

I have a timer that I want to start an AsyncTask when the countdown is done. If I put the execution of it in a handler it loops it and starts it many times. And if I dont put it in a Handler I get the following crash:
can't create handler inside thread that has not called looper.prepare()
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
private Handler mHandler = new Handler(Looper.getMainLooper());
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}
Any suggestions of how I can solve this?

AsyncTask is supposed to run on UI thread only. In your case, seems like you are not running it properly on a UI thread.
Perhaps try it like this:
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
Looper looper = Looper.getMainLooper();
looper.prepareMainLooper();
private Handler mHandler = new Handler(looper);
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}

By adding a handler outside of the TimerTask which I call from the TimerTask I could make it work!
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
RelativeLayout rl_header = (RelativeLayout)findViewById(R.id.rl_header);
Desktop desktop = helper.getDesktop();
try {
desktop.inflate(ll, rl_header, banners, DesktopApp.this);
Collections.sort(helper.nextListUpdate);
helper.nextListUpdate.remove(0);
timer = new Timer();
if (helper.nextListUpdate.size() > 0) timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
class ListUpdate extends TimerTask {
public void run() {
DesktopApp.this.runOnUiThread(new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(0);
}
});
}
}

Related

android implements runnable not working?

this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}

How update the UI from another thread in Android?

I searched for a way to update UI from another thread, and found that the available approach is to use Handler.post(Runnable) as shown in the code snippet below:
public class MyClass extends Activity {
private final Handler myHandler = new Handler();
final Runnable updateRunnable = new Runnable() {
public void run() {
// Update UI
}
};
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
myHandler.post(updateRunnable);
}).start();
}
};
}
Instead can't we use Handler.sendMessage and do the UI updates from main UI thread in handleMessage():
public class MyClass extends Activity {
private final Handler myHandler = new Handler();
private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
// Do logic here
}
}
};
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
myHandler.sendEmptyMessage(0);
}).start();
}
};
}
I'm sorry if this is a very basic question, however I'm quite confused with the above two approaches.
You need to use runOnUiThread. You can post a runnable which does the UI operation to main thread as follows,
public class Utils {
public static void runOnUiThread(Runnable runnable){
final Handler UIHandler = new Handler(Looper.getMainLooper());
UIHandler .post(runnable);
}
}
Utils.runOnUiThread(new Runnable() {
#Override
public void run() {
// UI updation related code.
}
});
Read more at:
android: update UI from another thread in another class
Updating UI / runOnUiThread / final variables: How to write lean code that does UI updating when called from another Thread
https://developer.android.com/training/multiple-threads/communicate-ui.html

Using Android Looper still throwing "Can't create handler inside..."

I have a looper and handler:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
updateUI(message.obj);
}
};
Looper.loop();
}
}
In my MainActivity I then call:
new LooperThread().start();
new Thread(new WorkerTask()).start();
Where WorkerTask implements Runnable.
Can't create handler inside thread that has not called Looper.prepare().
Inside my workerTask it is throwing the error on the second line:
locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If this is in Activity or fragment you can simply use runOnUiThread to update ui.
You need to use this:
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
Or to use it with your existing code:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
}
};
Looper.loop();
}
}

AsyncTask not called from TimerTask android

I am developing the project which continuously get datas from server at 30secs interval.So I used Handler with Timer and called Asynctask.
But my asynctask not called.This is my code,
final Handler handler;
handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask()
{
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try
{
System.out.println("I am xxx");
LiveTrack myActivity = new LiveTrack();
AsyncTask<String, String, String> task = myActivity.new VehiclePath();
task.execute();
}
catch (Exception e)
{
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 30000);
Can anyone guide me why I am facing this?
You cannot create an AsyncTask from within a TimerTask because it runs on a spawned thread, i.e.
not the UI thread).
AsynTasks must be created and execute()-ed only on the UI thread.
Instead, use an Executor for the background processing and call runOnUiThread when it is time to update the UI.
ExecutorService executorPool = Executors.newSingleThreadExecutor();
executorPool.execute(new Runnable() {
public void run() {
// do background processing here <------------------
myActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
// update ui here <--------------------
}
})
}
});

update data to server in the background android

How to update data to server ? I have used the code below but its not executing after 10 mins.
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(new Runnable(){
public void run() {
//update data to server
}
}, 0, 600, TimeUnit.SECONDS);
You must use your own Thread.
Here is solution using AsyncTask....
All code put in your Activity class.
public void toCallAsynchronous() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
MyAsyncTask task = new MyAsyncTask();
task.execute(txtSearchField.getText().toString());
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 2000); // execute in every 2 second
}
// AsyncTask Class
private class MyAsyncTask extends AsyncTask<String, Object, List<ModelObject>> {
#Override
protected List< ModelObject > doInBackground(String... params) {
// Call web service
return null;
}
#Override
protected void onPostExecute(List< ModelObject > result) {
super.onPostExecute(rezultat);
// Update UI
}
}
Try with this
private static final ScheduledExecutorService worker = Executors
.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable(){
public void run() {
//update data to server
}, 600, TimeUnit.SECONDS);

Categories

Resources