This is my code following,I am changing some iamges dynamically in my image view.
public class LoadingScreen extends Activity{
public static Integer[] imageList={R.drawable.food_pics1,R.drawable.food_pics2,R.drawable.food_pics3,
R.drawable.food_pics4,R.drawable.food_pics5,R.drawable.food_pics6,R.drawable.food_pics7,
R.drawable.food_pics8,R.drawable.food_pics9};
Thread thread;
ImageView foodImageView;
final Handler myHandler=new Handler();
public int currentImageIndex=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.load_xml);
foodImageView=(ImageView)findViewById(R.id.imageView_food);
// final int i=0;
final Runnable runnable = new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
animateImages();
}
};
final int delay=500;
final long period=1000;
Timer timer=new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
myHandler.post(runnable);
}
}, delay, period);
}
private void animateImages() {
// TODO Auto-generated method stub
foodImageView.setImageResource(imageList[currentImageIndex%imageList.length]);
currentImageIndex++;
foodImageView.getAnimation();
}
I want to stop the timer and finish this activity after 20 secs.how can I do that.
Try using this,
View v = new View(this);
v.postDelayed(new Runnable(){
public void run() {
// TODO Auto-generated method stub
//cancel your animation and finish the Activity here.
finish();
}
}, (long) 20000.0);
You can say something like this :
timer.cancel();
timer = null;
Save the TimerTask instance in the class and invoke cancel on it.
Here's a tip I found very useful without using Java's Timer: Try synchronizing things in the UI thread, especially if you want to do UI tasks. Example:
... onCreate() {
getUiThreadHandler().post(new Runnable(){
if (canceled()) {
return;
}
// Actual work
...
// Invoke again after delay
getUiThreadHandler().postDelayed(this, 500);
});
Good luck
Related
I would like to call the same method, say every 5 seconds, I am trying to create some sort of database listener that will listen for database changes. The following code does not work, I am expecting the log to print "RUNNING" every 5 seconds for testing but this only gets called once when I call the method for the first time.
private void DBListern() {
// TODO Auto-generated method stub
//accessWebService();
System.out.println("RUNNING");
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
DBListern();
}
}, 5000);
}
Take a look at java.util.concurrent.ScheduledExecutorService with its scheduleAtFixedRate you should be able to do exactly what you want!
Try to use java.util.concurrent.ScheduledExecutorService.
Example:
private final ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
private void DBListern(int delayInSeconds) {
//accessWebService();
System.out.println("RUNNING");
exec.schedule(new Runnable() {
#Override
public void run() {
DBListern();
}
}, delayInSeconds, TimeUnit.SECONDS);
}
Ok, for some reason the function cannot call itself so I created a different function called loop() which calls DBListern every 5 seconds:
private void DBListern() {
// TODO Auto-generated method stub
//accessWebService();
System.out.println("RUNNING");
}
private void loop() {
// TODO Auto-generated method stub
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
DBListern();
handler.postDelayed(this, 5000);
}
}, 5000);
}
So loop() is called first and then it calls DBListern every 5 seconds.
When I press this button:
case R.id.btlento:
Timer timers = new Timer();
timers.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
cameraOn();
},deloy1,poriod1);
Timer timers2 = new Timer();
timers2.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
cameraOff();
}
},deloy,poriod);
The methods cameraOn and cameraOff are:
private void cameraOff() {
// TODO Auto-generated method stub
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
}
private void cameraOn() {
// TODO Auto-generated method stub
camera = Camera.open();
parameters = camera.getParameters();
parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(parameters);
}
and the variables are:
int deloy = 2000;
int poriod = 2000;
int deloy1 = 1000;
int poriod1 = 2000;
All this is to make the camera flash blink, but I don't know how break the loop, because never stops.
How can i stop the loop?
Use a flag,
// member variables
private boolean cameraIsFlashing = false;
private Timer onTimer;
private Timer offTimer;
// constructor & other stuff
// button click method
case R.id.btlento:
toggleCameraFlash();
break;
private void toggleCameraFlash(){
if(cameraIsFlashing){
stopFlashing();
} else {
startFlashing();
}
}
private void startFlashing(){
cameraIsFlashing = true;
// Start your timers
onTimer = new Timer();
onTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
cameraOn();
},deloy1,poriod1);
}
private void stopFlashing(){
cameraIsFlashing = false;
// Cancel / Stop your timers
onTimer.cancel;
}
call cancel() and purge() on thread timer to stop the thread.
as shown below.
private void cameraOff() {
// TODO Auto-generated method stub
if(timer != null){
parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(parameters);
camera.release();
camera = null;
timer.cancel();// cancel and releases
timer.purge();
}
}
Make a variable for timer task instead of using anonymous class. First cancel timer task then cancel timer.
I'm having trouble with something that seems like it should be very simple. I have a frame layout with 2 Buttons (one on top of the other naturally). When I click on the top button, it automatically takes me to a website, and the button beneath it replaces it to be the visible one. I want to set up an automatic refresh so that a few seconds later, the button that was originally on top becomes on top again. Thank you for any help you can give! Here is the Java, and with my attempt at creating an automatic refresh:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton bJava1= (ImageButton)findViewById(R.id.button1);
final ImageButton bJava2 = (ImageButton)findViewById(R.id.button2);
final WebView webview1= (WebView)this.findViewById(R.id.webView1);
final MediaPlayer sound= MediaPlayer.create(Youtube.this, R.raw.soundclip1);
final Handler handler = new Handler();
Refresh = new Runnable() {
public void run() {
bJava1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
webview1.loadUrl("http://www.google.com");
if(sound.isPlaying()){
bJava1.setVisibility(ImageButton.VISIBLE);
bJava2.setVisibility(ImageButton.GONE);
}else {
sound.start();
bJava1.setVisibility(ImageButton.GONE);
bJava2.setVisibility(ImageButton.VISIBLE);
}
}
});
handler.postDelayed(Refresh, 10000);
}
};
handler.post(Refresh);
Problem is, that your Refresh runnable only registers a onClickListener on the first button and calls itself every 10 seconds, you should register the onClickListener only once outside the Runnable and only call the if block within your Refresh.run() Method:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageButton bJava1= (ImageButton)findViewById(R.id.button1);
final ImageButton bJava2 = (ImageButton)findViewById(R.id.button2);
final WebView webview1= (WebView)this.findViewById(R.id.webView1);
final MediaPlayer sound= MediaPlayer.create(Youtube.this, R.raw.soundclip1);
final Handler handler = new Handler();
Refresh = new Runnable() {
public void run() {
if(sound.isPlaying()){
bJava1.setVisibility(ImageButton.VISIBLE);
bJava2.setVisibility(ImageButton.GONE);
}else {
sound.start();
bJava1.setVisibility(ImageButton.GONE);
bJava2.setVisibility(ImageButton.VISIBLE);
}
}
};
bJava1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
webview1.loadUrl("http://www.google.com");
handler.postDelayed(Refresh, 10000);
}
});
public Button stb;
static int cnt=0;
public ArrayList<RadioButton> Butgrp1 = new ArrayList<RadioButton>();
Timer myt;
TimerTask t;
stb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
myt.mschedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
System.out.println("Entering run");
Handler h=new Handler();
h.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
}
});
//rg.getChildAt(cnt).setPressed(true);
}
},1000,2000);
I need to access a group of radio buttons on the ui and set it as checked at regular intervals, but i keep getting different errors, i realized i must use a handler, but its still not working...can anyone please tell me where i am going wrong....am a newbie and am trying out stuff to understand the working better...please help...
You have to create the Handler in the UI Thread, i.e. in onCreate of your Activity.
Because you create it in the run method of a background thread, the handler will execute your code in that very same background thread.
You could also initialize your Handler directly:
public class MyActivity extends Activity{
private Handler handler = new Handler();
//more code
}
And then don't use runOnUIThread:
handler.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
EDIT:
Ok try this cleaned up code. Because you did not post your full Activity this won't work out of the box:
public class TestActivity extends Activity {
private Button button;
static int cnt=0;
public ArrayList<RadioButton> buttonArray = new ArrayList<RadioButton>();
private Timer timer = new Timer();
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
timer.schedule(new MyTimerTask(), 1000,2000);
}
});
}
private void doButtonStuff(){
buttonArray.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4){
cnt=0;
}
if(cnt>0){
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
}
private class MyTimerTask extends TimerTask{
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
doButtonStuff();
}
});
}
}
}
You can pass the Activity as a parameter to the method that runs the timertask, and then you can use Activity.runOnUiThread to execute your tasks in UI Thread. There are lots of post in stackoverflow site regarding the usage of runOnUiThread usage.
You don't need to call runOnUIThread inside the handler. By calling post on the Handler instance, the runnable you pass will be executed on the UI thread at some point in the future. Change your code to look like this and it should work:
Handler h=new Handler();
h.post(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Butgrp1.get(cnt).setChecked(true);
cnt=cnt+1;
if(cnt>4)
cnt=0;
if(cnt>0)
// Butgrp1.get(cnt-1).setChecked(false);
System.out.println(cnt);
}
});
This is my Service class:
public class MySrv extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final Context c = getApplicationContext();
Timer t = new Timer("mytimer");
TimerTask task = new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show();
}
};
t.schedule(task, 5000, 6000);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The application crashes at Toast.makeText()... So what am I doing wrong?
The TimerTask's run() method doesn't execute in the UI thread, so you can't do UI-related things like creating a Toast.
Investigate using a Handler or runOnUiThread() instead.
Example:
final Handler handler = new Handler ();
TimerTask task = new TimerTask() {
#Override
public void run() {
handler.post (new Runnable (){
#Override
public void run() {
Toast.makeText(c, "Not a beautyfull day today...", Toast.LENGTH_SHORT).show();
}
});
}
The problem here is that you are trying to update the UI in the timers thread, you should use a Handler for this.
Read How to display toast inside timer?
You cannot make a Toast in another Thread, you can use a Handler to do it or use the runOnUiThread.
public class YourActivity extends Activity {
private Handler toastTeller;
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
toastTeller = new Handler() {
public void handleMessage(Message msg) {
if (msg.what == 2)
Toast.makeText(LibraryActivity.this, msg.obj.toString(),
Toast.LENGTH_LONG).show();
super.handleMessage(msg);
}
};
new Thread(new Runnable(){
public void run(){
Message msg = new Message();
msg.what = 2;
msg.obj = "Your item was downloaded.";
toastTeller.sendMessage(msg);
}
}).start();
}