Timer class in android or a Handler timer?
android.os.Handler
is part of Android framework, the job will execute on the UI or main thread if you have created the Handler in the UI or main thread. Note that in Android you can only update views from the UI thread.
java.util.Timer
on the other hand will execute on another thread so it cannot update the views.
So Handler is the recommended here. If you really want to use Timer you have to use runOnUiThread
like:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//this will run on UI thread so you can update views here
}
});
}
}, 2000, 2000);
TimerTask vs Thread.sleep vs Handler postDelayed - most accurate to call function every N milliseconds?
There are some disadvantages of using Timer
- It creates only single thread to execute the tasks and if a task
takes too long to run, other tasks suffer. - It does not handle
exceptions thrown by tasks and thread just terminates, which affects
other scheduled tasks and they are never run
ScheduledThreadPoolExecutor deals properly with all these issues and it does not make sense to use Timer.. There are two methods which could be of use in your case.. scheduleAtFixedRate(...) and scheduleWithFixedDelay(..)
class MyTask implements Runnable {
@Override
public void run() {
System.out.println("Hello world");
}
}
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
long period = 100; // the period between successive executions
exec.scheduleAtFixedRate(new MyTask(), 0, period, TimeUnit.MICROSECONDS);
long delay = 100; //the delay between the termination of one execution and the commencement of the next
exec.scheduleWithFixedDelay(new MyTask(), 0, delay, TimeUnit.MICROSECONDS);
Android Handler for repeated task - will it overlap ? Timer-task VS handler VS alarm-manager
I decided to answer my own question since I've found out how to do it right way. The Android way. First of all what I was trying to do and posted in the question is a wrong approach to my requirement. Now I'm posting this so someone else will not do it wrong way but the following way.
Android has few options for timing.
Timer-task -> runs while application is alive. best for short term timing. Resource usage is higher.
Handler -> runs while application is alive. But not suitable to used as a scheduler. (this is what I've asked and it's not the correct way to do that).
Handlers
are the best way to do something repeatedly till the app is killed.- Alarm-manager -> The best way to schedule something to happen in future even if the app is killed. (this is what I should apply for my app).
This is what I figured out. Correct me if I'm wrong.
handler or chronometer or timertask or countdowntimer which I should use for showing countdowntimer in UI and doing some operation after time is up?
You should use a Handler, here's an example:
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//Do something after 100ms
}
}, 100);
If you'd like to terminate the handler at any time, you can call:
handler.removeCallbacks(myRunnable);
From the docs:
public final void removeCallbacksAndMessages (Object token)
Added in API level 1
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
TimerTask and Handler for showing the pictures every seconds in android
Try it this way:
public class MainActivity extends ActionBarActivity {
final Handler handler = new Handler();
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView1);
}
@Override
protected void onResume() {
super.onResume();
initialize();
}
public void initialize() {
Runnable runnable = new Runnable() {
@Override
public void run() {
/* do what you need to do */
new DownloadImageTask(imageView).execute("http://url/background1.jpg");
/* and here comes the "trick" */
handler.postDelayed(this, 3000);
}
};
handler.postDelayed(runnable, 3000);
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
You also had your ImageView not referenced on the onCreate
method. That possibly created a NullPointerException
.
Related Topics
Google Map Signed API Key Errors in Android
Slowing Speed of Viewpager Controller in Android
Custom Filtering in Android Using Arrayadapter
Streaming Video from Android Camera to Server
Android Backup/Restore: How to Backup an Internal Database
Programmatically Scroll to a Specific Position in an Android Listview
How to Increase Storage for Android Emulator? (Install_Failed_Insufficient_Storage)
Cannot Get Searchview in Actionbar to Work
Replace Getmap with Getmapasync
How to Change the Android Actionbar Title and Icon
What Are Advantages of Setting Largeheap to True
How to Monitor the Network Connection Status in Android
Difference Between .Getpath() VS Cursor in Getting the Real Path of a File from Uri in Android
How to Draw an Overlay on a Surfaceview Used by Camera on Android
Deleting Row in SQLite in Android