How to display images on Map View with an interval? - android

I want to display 5 images on a Map View as map overlay with an interval of 1 minute each. I use sleep to make a delay. But it is not working. After all delay, the images are displaying altogether. How to do this? Please help

Look at this link. I think, it is, what you need
http://developer.android.com/resources/articles/timed-ui-updates.html
UPD:
Define in your activity:
private Handler mHandler = new Handler();
private int cnt = 0;
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
if (cnt < 5)
{
// Display new Image
mHandler.postDelayed(mUpdateTimeTask, 60000);
cnt++;
}
else
{
mHandler.removeCallbacks(this);
}
}
};
and call then somwhere in onCreate or onResume
mHandler.postDelayed(mUpdateTimeTask, 60000);

Related

Multiple Runnables on one handler, wrong repeat behaviour

In my android application I need to update different parts of the UI (actually a Fragment inside a ViewPager on a different time intervals. To do this I've created an Handler and 3 Runnables. With the postDelayed(Runnable, delay) method the Runnables should repeat themselves at scheduled time intervals.
Currently I have 1 runnable that must update a TextView every 100 ms, another that update a ProgressBar every 1000 ms and another one that checks some stuff every 2000 ms.
I saw the counter and the progress bar incrementing too fast and so I've put some code checking the delay between every call to the Run() method and I've discovered that the first runnable is executed every 58 ms and the progressbar's one running every 508 ms.
I've then tried to left only the first Runnable on the Handler (the counter one) and the Run() method get called every ~101 ms. So I've hypothized that other Runnables maybe interfer with the Message Queue schedule. I've then created one Handler for every Runnable but in that way the problem persist with 56~58 ms in the first Runnable and 508~510 ms on the second one.
Any suggestion on why this behaviour happen?
Here's part of my code:
private static final int TIME_STEP_COUNTER = 100;
private static final int TIME_STEP_PROGRESS = 1000;
private static final int TIME_STEP_DIRECTOR = 2000;
private Handler counterHandler, progressHandler, directorHandler;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// some code here
directorThread = new DirectorThread(wwp,TIME_STEP_DIRECTOR);
if(directorHandler == null){
directorHandler = new Handler();
directorHandler.post(directorThread);
}
startCounting();
}
StartCounting() method
public void startCounting(){
stdCounterUpdater = new CounterUpdaterThread(textViewCounter,TIME_STEP_COUNTER, increment100ms);
progressUpdaterThread = new ProgressUpdaterThread(progressBar,TIME_STEP_PROGRESS,textViewPercentage);
fixerThread = new FixerThread(wwp,TIME_STEP_FIXER);
if(counterHandler == null){
counterHandler = new Handler();
}
counterHandler.post(stdCounterUpdater);
if(progressHandler == null){
progressHandler = new Handler();
}
progressHandler.postDelayed(progressBarInitThread, DELAY_INIT_PROGRESS);
progressHandler.postDelayed(progressUpdaterThread, DELAY_INIT_PROGRESS + INIT_PROGRESS_DURATION);
counterLayout.setVisibility(View.VISIBLE);
}
Threads
CounterUpdater
class CounterUpdaterThread implements Runnable{
public CounterUpdaterThread(TextView counterView, long deltaTime, float increment){
//Constructor with fields initialization
}
#Override
public void run(){
counter += increment;
changeCounterText();
if(counterHandler != null){
counterHandler.postDelayed(stdCounterUpdater,deltaTime);
}
}
}
ProgressUpdater
class ProgressUpdaterThread implements Runnable{
public ProgressUpdaterThread(ProgressBar pBar, long deltaTime, TextView percTW){
//Fields init
}
#Override
public void run(){
anim = new ProgressBarAnimation(progressBar, progress, progress + smoothScale);
progress += smoothScale;
anim.setDuration(PROGRESS_UPDATE_DURATION);
progressBar.startAnimation(anim);
percTW.setText(String.format(Locale.US,"%.1f", progressBar.getProgress()*100f/progressBar.getMax()) + "%");
if(progressHandler != null){
progressHandler.postDelayed(progressUpdaterThread,deltaTime);
}
}
}
DirectorThread
class DirectorThread implements Runnable{
public DirectorThread(WeeklyWorkPeriod wwp, long deltaTime){
//init
}
#Override
public void run(){
if(isStarted){
//....code.....
stopCounting();
isStarted = false;
//....code.....
}
}
else{
// ...code...
raiseMethod.requestProgressData(ProgressBarFragment.this,fragmentID);
startCounting();
isStarted = true;
}
}
if(directorHandler != null){
directorHandler.postDelayed(directorThread,deltaTime);
}
}
}
I've checked also these articles and some other question but with no results
Repeating Tasks
Handler Vs Timer
Handlers and Loopers
I just found the problem: wasn't about a single handler but about starting new callbacks in the DirectorThread. Just setting in the onCreateView() method isStarted to true solved the problem.
Among the other things I've replaced postDelayed() with postAtTime() as suggested by pskink cause it happens to be more accurate.

Android view doesn't update when trying to set values over time

I got a fragment which got a control called RingProgress which is simply a ring that fills itself according to a percentage value given. For example, if I do:
ringProgress.setProgress(20);
It means that 20% of the ring will now be filled.
What I'm trying to do is to animate the ring being filled over a few seconds. So what I've tried to do is this:
#Override
public void onResume()
{
super.onResume();
HandlerThread handlerThread = new HandlerThread("countdown");
handlerThread.start();
Handler handler = new Handler(handlerThread.getLooper());
handler.post(new Runnable()
{
#Override
public void run()
{
final Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
int totalSeconds = secondsToStart + minutesToStart * 60;
int secondsPassed = 0;
#Override
public void run()
{
if(secondsPassed == totalSeconds)
{
timer.cancel();
}
final int currentProgress = (secondsPassed / totalSeconds) * 100;
secondsPassed++;
getActivity().runOnUiThread(new Runnable()
{
#Override
public void run()
{
mRingProgressBar.setProgress(currentProgress);
}
});
}
}, 0, 1000);
}
});
}
The problem is that the update of the ring is not shown until the time is up. For example, if I set it for 5 seconds then when the fragment loads the ring is set to 0, then nothing happens for 5 seconds and then the ring is full with 100% all at once..
How can I start this animation properly?
I guess the problem is with
final int currentProgress = (secondsPassed / totalSeconds) * 100;
secondsPassed / totalSeconds return int value so it will be 0 or 1 only. And you multiply it to 100.
You have to use float or double instead
something like
final int currentProgress = Math.round(((float) secondsPassed)/((float) totalSeconds)*100f);
On this line:
Handler handler = new Handler(handlerThread.getLooper());
You are trying to get the looper from a handlerThread. But how sure you are the looper has already been initialized?
From the documentation of getLooper()
This method returns the Looper associated with this thread. If this thread not been started or for any reason is isAlive() returns false, this method will return null. If this thread has been started, this method will block until the looper has been initialized.
onLooperPrepared() is the callback, where you can be sure, that the Looper has been initialized, and therefore you can construct logics on that.
Thus, what you have to do, is to subclass HandlerThread and create appropriate logics from onLooperPrepared() callback.
Here's a nice post which will help you out. See implementation of MyWorkerThread class there.
Instead of using a handler, you could use a property animator as follows:
ObjectAnimator.ofInt(mRingProgressBar, "progress", 0, 100)
.setDuration(totalSeconds * 1000) //time is in miliseconds
.start();
This will find a method setProgress() in your mRingProgressBarand set the value according to the limits given. In the example above, 0 to 100.
You can read more about it here
Since you want to run on a different thread, you can use this handler in the top of the class:
private int progress = 0;
Handler timerHandler = new Handler();
Runnable timerRunnable = new Runnable() {
#Override
public void run() {
ringProgress.setProgress(progress);
progress += 20;
if (progress == 100) { //clear??
}
timerHandler.postDelayed(this, 1000);
}
};
In inCreate set the max:
ringProgress.setMax(100);
This will complete the animation within 5 seconds, then you can clear the animation. If you want smaller increments, change the line below (update every tenth of a second), and change the steps
timerHandler.postDelayed(this, 100);

How do I delay imageviews from changing

Hello I'm trying to delay imageviews to give a perception that they are being taken out one by one. I've tried
Thread.Sleep
CountDownTimer
Runnable/Handler
But they either only delay once and both imageviews change at the same time or do not delay at all. For some reference I'm trying to do something like
private void delaycard(final int Card) {
newcard(Card); //Delay this before it is called
}
Willing to try/retry anything at this point
Off the top of my head, try something like this:
Handler h = new Handler();
//for the number of images we have
for (int i = 0; i < numImages; i++) {
//we create a runnable for that action
Runnable r = new Runnable() {
#Override
public void run() {
newCard(card);
}
};
//this is the amount of time to delay it by
delay = delay + 500;
//effectively, we're creating a series of runnables at the same time
//but they activate one after the other in .5s intervals
h.postDelayed(r, delay);
}
put this inside your method
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
newCard(Card);
}
}, 100);

I get response from server and I want to save these images url in an array .and show one image at a time after ten seconds image change

For example I get three images in response from a web service and I want to show one image at a time in screen ..After every ten seconds image should change itself....how this can be done?
The code under the run(){} method will repeat after a interval of time mentioned.
// make global variables
int 1=0;
private Handler handler;
Timer timer;
Runnable mUpdateResults;
// Declare ArrayList of type Bitmaps
final ArrayList<Bitmap> images = new ArrayList<Bitmap>();
// get the images from drawable folder and convert it into bitmaps plus add them in arrayList
images.add(BitmapFactory.decodeResource(this.getResources(),R.drawable.ic_launcher));
images.add(BitmapFactory.decodeResource(this.getResources(), R.drawable.one));
images.add(BitmapFactory.decodeResource(this.getResources(), R.drawable.two));
// get the imageview
final ImageView a = (ImageView)findViewById(R.id.imageView1);
timer = new Timer();
handler = new Handler();
mUpdateResults = new Runnable() {
public void run() {
// checking if i==0 so set first image.. similarly so on
if(i == 0)
{
a.setImageBitmap(images.get(0));
}
if(i ==1)
{
a.setImageBitmap(images.get(1));
}// .. add more if you like
i++;
}
}
};
int delay = 1000 ; // you can adjust it according to your need
int period = 8000; // you can adjust it according to your need
// execute timer
timer.scheduleAtFixedRate(new TimerTask() {
public void run(){handler.post(mUpdateResults); }}, delay, period);
for stopping the timer
handler.removeCallbacksAndMessages(mUpdateResults);
timer.cancel();
here
delay--This is the delay in milliseconds before task is to be executed.
period--This is the time in milliseconds between successive task executions.

How to change a TextView every second in Android

I've made a simple Android music player. I want to have a TextView that shows the current time in the song in minutes:seconds format. So the first thing I tried was to make the activity Runnable and put this in run():
int position = 0;
while (MPService.getMP() != null && position<MPService.duration) {
try {
Thread.sleep(1000);
position = MPService.getSongPosition();
} catch (InterruptedException e) {
return;
}
// ... convert position to formatted minutes:seconds string ...
currentTime.setText(time); // currentTime = (TextView) findViewById(R.id.current_time);
But that fails because I can only touch a TextView in the thread where it was created. So then I tried using runOnUiThread(), but that doesn't work because then Thread.sleep(1000) is called repeatedly on the main thread, so the activity just hangs at a blank screen. So any ideas how I can solve this?
new code:
private int startTime = 0;
private Handler timeHandler = new Handler();
private Runnable updateTime = new Runnable() {
public void run() {
final int start = startTime;
int millis = appService.getSongPosition() - start;
int seconds = (int) ((millis / 1000) % 60);
int minutes = (int) ((millis / 1000) / 60);
Log.d("seconds",Integer.toString(seconds)); // no problem here
if (seconds < 10) {
// this is hit, yet the text never changes from the original value of 0:00
currentTime.setText(String.format("%d:0%d",minutes,seconds));
} else {
currentTime.setText(String.format("%d:%d",minutes,seconds));
}
timeHandler.postAtTime(this,(((minutes*60)+seconds+1)*1000));
}
};
private ServiceConnection onService = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder rawBinder) {
appService = ((MPService.LocalBinder)rawBinder).getService();
// start playing the song, etc.
if (startTime == 0) {
startTime = appService.getSongPosition();
timeHandler.removeCallbacks(updateTime);
timeHandler.postDelayed(updateTime,1000);
}
}
what about this:
int delay = 5000; // delay for 5 sec.
int period = 1000; // repeat every sec.
Timer timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask()
{
public void run()
{
//your code
}
}, delay, period);
Use a Timer for this (instead of a while loop with a Thread.Sleep in it). See this article for an example of how to use a timer to update a UI element periodically:
Updating the UI from a timer
Edit: updated way-back link, thanks to Arialdo: http://web.archive.org/web/20100126090836/http://developer.android.com/intl/zh-TW/resources/articles/timed-ui-updates.html
Edit 2: non way-back link, thanks to gatoatigrado: http://android-developers.blogspot.com/2007/11/stitch-in-time.html
You have to use a handler to handle the interaction with the GUI. Specifically a thread cannot touch ANYTHING on the main thread. You do something in a thread and if you NEED something to be changed in your main thread, then you call a handler and do it there.
Specifically it would look something like this:
Thread t = new Thread(new Runnable(){
... do stuff here
Handler.postMessage();
}
Then somewhere else in your code, you do
Handler h = new Handler(){
something something...
modify ui element here
}
Idea its like this, thread does something, notifies the handler, the handler then takes this message and does something like update a textview on the UI thread.
This is one more Timer example and I'm using this code in my project.
https://stackoverflow.com/a/18028882/1265456
I think the below blog article clearly gives a very nice solution. Especially, if you are a background service and want to regularly update your UI from this service using a timer-like functionality.
It really helped me, much more than the 2007 blog link posted by MusiGenesis above.
https://www.websmithing.com/2011/02/01/how-to-update-the-ui-in-an-android-activity-using-data-from-a-background-service/

Categories

Resources