I have searched about kill the Runnable but i could not find the true answer with this code.I have tried boolean and stop() method.Can somebody help me to kill this runnable? Thanks.
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.close);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
myL.setBackgroundResource(R.drawable.open);
}
});
}
}
};
new Thread(runnable).start();
you can set your exit condition:
private class MyThread extends Thread {
private boolean volatile exit = false;
#Override
public void run() {
while(!exit) {
}
}
public void stopMyThread() {
exit = true;
}
}
and from your code you call
myThreadInstance.stopMyThread();
when you need to make you run method finish
You are repeating infinitely a one-second-wait. This will never stop. You need to have a boolean flag which will serve as the continue/stop condition and you need to negate its value when the Thread needs to stop.
If you want to stop it from another Thread, then call Thread.interrupt.
Related
i am calling this medthod show() in onCreate()
, whats wrong in my code
public void show()
{
Toast.makeText(getApplicationContext(),"1",Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
Looper.prepare();
Toast.makeText(getApplicationContext(),"2",Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"3",Toast.LENGTH_SHORT).show();
int arr[]={R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4};
int i=1;
do
{
i++;
try
{
imageView.setImageResource(arr[i]);
Thread.sleep(2000);
}
catch (InterruptedException e) {e.printStackTrace();}
}
while(i==arr.length);
}
},2000);
}
}).start();
}
i think it should wait for 2 sec. every time and show next image but its doing nothing even no error
i used toast to counter processing then i found its only reaching to first toast
I am trying to update seekbar with respect to the progress of the song in MediaPlayer.
I am using Thread to do that task.
First i have used Thred inside thread and trying to update the UI but it crashing the app and says that only original thread can attached to the view.
Then i have try to update it with handler inside the thread runnable. which works fine but it is not updating the seekbar. When i have do log then i come to know loop is not going inside my handler. I dont know where is the problem. Please help me to updating SeekBar.
Code:
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
try {
if ((musicPath != mIRemoteService.getPath())) {
System.out.println("..... MUSIC CHANGE.....");
setOrUpdateData();
updateFragmentLayout();
}
// Displaying Current Duration time/Progress
new Handler().post(new Runnable() {
#Override
public void run() {
try {
songCurrentDurationLabel.setText(""+ Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int)mIRemoteService.position());
System.out.println("Runnnnn.........");
//songProgressBar.invalidate();
} catch (RemoteException e) {
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
System.out.println("Runnnnn.........MAIN....");
if (!(mIRemoteService.isPlayerRunning())) {
btnPlay.setImageDrawable(getResources().getDrawable(R.drawable.play_now_playing));
mHandler.removeCallbacks(mUpdateTimeTask);
System.out.println("Runnnnn.........MAIN....IF");
}else{
System.out.println("Runnnnn.........MAIN....ELSE");
mHandler.post(mUpdateTimeTask);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
you can use either a handler or a thread, with thread you should make sure to post the modifications on the UI thread:
private class UpdateSeekBar extends Thread
{
#Override
public void run()
{
super.run();
while (null != mp && mp.isPlaying() && this.isAlive())
{
//final int min = (mp.getCurrentPosition() / 1000) / 60;
//final int sec = (mp.getCurrentPosition() / 1000) % 60;
MainActivity.this.runOnUiThread(new Runnable()
{
#Override
public void run()
{
try
{
songCurrentDurationLabel.setText("" + Utilities.milliSecondsToTimer(mIRemoteService.position()));
songProgressBar.setProgress((int) mIRemoteService.position());
System.out.println("Runnnnn.........");
// songProgressBar.invalidate();
}
catch (RemoteException e)
{
e.printStackTrace();
System.out.println("Runnnnn......... EXCEPTION....");
}
}
});
try
{
Thread.sleep(1000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
}
I have Runnable and have two Handlers for button background color change after some music is played.
Now how can I stop the music played using runnable for a ever delay of 700 mili sec on a button click named stop.
handler=new Handler();
runnable = new Runnable() {
#Override
public void run() {
for (int i = 0; i<Uirkeys1.length; i++) {
final int value = i;
try {
Thread.sleep(700);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
copyView.get(cnt1).getBackground().setAlpha(100);
ModeSound(Integer.parseInt(CopyMultimap.get(copykey[cnt1]).get(3)));
}
});
try {
Thread.sleep(800);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run()
copyView.get(cnt1).getBackground().setAlpha(500);
cnt1++;
}
});
}
}
};
new Thread(runnable).start();
cnt1=0;
}
});
}
You could create a class MyRunnable that implements Runnable, and create a field in it
private boolean stopped = false;
public void stop() { stopped = true; }
And then you should check in your execution loop
if(!stopped) {..do work..} else return .
And you can of course call the stop() method on your MyRunnable object.
I am starting a thread when invoking a method to play an audio file.
The code runs ok the first time but when I call the play method again I need the thread to start as if it were being called the first time. I have tried to interrupt the thread and even stop it but nothing seems to work.
How can I properly restart the thread?
Here is some code to help explain.
Global variable
private Thread thread1;
Thread code:
thread1 = new Thread(new Runnable()
{
#Override
public void run()
{
try {
int i=0;
final TextView timeDuration = (TextView) findViewById(R.id.timeDisplay);
final SeekBar seekBar = (SeekBar)findViewById(R.id.seekBar1);
while (running)
{
info();
j = 0;
while(i>0 && running)
{
while(j<duration && running && (playStatus.getValue() == "TRANSITIONING" || playStatus.getValue() == "PLAYING"))
{
seekBar.setMax((int) duration);
seekBar.setProgress(0);
runOnUiThread(new Runnable()
{
public void run()
{
System.out.println("PLAYBACK STATUS: "+playStatus.getValue());
timeDuration.setText(""+(j+1));
seekBar.setProgress(j+1);
if(j==(duration-1))
{
setRunning(false);
}
}
});
Thread.sleep(1 * 1000);
j++;
if(seekBar.getProgress() == seekBar.getMax())
{
runOnUiThread(new Runnable()
{
public void run()
{
playButton.setVisibility(View.VISIBLE);
pauseButton.setVisibility(View.GONE);
timeDuration.setText(""+"0");
seekBar.setProgress(0);
flag = false;
System.out.println("J VALUE 1: = "+j);
duration = 0;
setRunning(false);
}
});
}
}
}
j = 0;
i++;
Thread.sleep(1 * 1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
play();
This code works fine and plays the track. It then resets the seekbar and awaits for the play method to be called again.
public void play()
{
try
{
thread1.start();
}
catch(Exception e)
{
return;
}
}
Here is the setRunning method recommended to me.
public void setRunning(boolean b)
{
this.running = b;
}
If anyone know of a solution to this problem I would really appreciate it.
Threads are not supposed to be stopped manually. You should use a boolean instead of true in your while loop, and put the boolean to false through a setter when you want to stop:
private boolean running;
#Override
public void run(){
running = true;
while(running) {...}
}
public void setRunning(boolean b){
this.running = b;
}
To restart your player you need to prepare again.
public void restartAudio() {
Log.e(TAG, "restartAudio");
if (mp.isPlaying()) {
mp.seekTo(0);
}else{
mp.stop();
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When using extra boolean flag to controll thread's while loop don't forget to use volatile modifier on it:
private volatile boolean running;
or put appropriate synchronization.
Apart from that, I'd think about using Thread.isInterrupted() method instead of the additional 'running' flag:
http://docs.oracle.com/javase/6/docs/api/java/lang/Thread.html#isInterrupted()
here's why:
https://stackoverflow.com/a/3196058/1350225
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ThraedDemo objDemo = new ThraedDemo();
Thread objThread = new Thread() {
#Override
public void run() {
objDemo.firstMethod();
}
};
objThread.start();
}
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
private void secondMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
((ImageView)findViewById(R.id.ImageViewResult)).setImageResource(nums[n+1]);
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
firstMethod();
}
};
objThread.start();
}
};
objThread.start();
}
}
I use the above code but it is not running.it got CalledFromWrongThreadException what is the problem inb the above code.Please give me some suggestions.Thanks in advance
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
I edited your 2nd function code, I see your code is loop forever cause the firstMethod call secondMethod and the secondMethod call the new firstMethod to start and then loop forever. I removed it and moved the code update ImageView into the UI Thread, could you try this:
class ThraedDemo {
private void firstMethod() {
Thread objThread = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n]);
}
});
Thread.sleep(10000);
Log.v("Thread","1111111111111111sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
secondMethod();
}
};
objThread.start();
}
private void secondMethod() {
Thread objThread2 = new Thread() {
#Override
public void run() {
try {
runOnUiThread(new Runnable() {
public void run(){
((ImageView)findViewById(R.id.ImageViewnumber)).setImageResource(nums[n+1]);
}
});
n++;
Thread.sleep(10000);
Log.v("Thread","22222222222 sleep");
} catch (InterruptedException ex) {
System.out.println("interuped exception" + ex.getMessage());
}
}
};
objThread2.start();
}
}