I need animate menu in custom view. It must be redrawed with intervals some times(about 10), but it redraws after thread stopped.
public void menuShift() {
Runnable runnable = new Runnable() {
public void run() {
while (TablesActivity.this.view.menuShifting) {
try {
Thread.sleep(100) ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
TablesActivity.this.view.timerRefresh() ;
TablesActivity.this.view.postInvalidate() ;
}
}
} ;
this.menuShiftThread = new Thread(runnable) ;
this.menuShiftThread.run() ;
}
this.menuShiftThread.run(); is the problem, you need
this.menuShiftThread.start()
to actualy start a new thread.
Related
I'm trying to change a textView from my thread, but it always crashes. Why?
public void startProgress(View view) {
bar.setProgress(0);
new Thread(new Task()).start();
}
class Task implements Runnable {
#Override
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bar.setProgress(value);
text.setText("i = "+i);
}
}
}
I don't know why i can't change it. Anyone knows why?
Thanks.
Views can only be modified by their parent thread. This is a common problem that people face, unfortunately you just have to work around it.
Use runOnUiThread
runOnUiThread(new Runnable(){
public void run() {
for (int i = 0; i <= 10; i++) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
bar.setProgress(value);
text.setText("i = "+i);
}
}
});
As #dodo or #CommonsWare said you must access View hiearhcy in the main ui thread.
To comply with this rule, use Handler.post(Context.getMainLooper())
new Handler(context.getMainLooper()).post(new Runnable() {
public void run() {
bar.setProgress(value);
text.setText("i = "+i);
}
});
Finally I fixed it. Thanks anyway.
public void startProgress(View view) {
bar.setProgress(0);
//new Thread(new Task()).start();
Thread th = new Thread(new Runnable() {
public void run() {
for (int i=0; i<10;i++){
final int timer = i;
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText("velocitat: "+timer);
}
});
bar.setProgress(timer);
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
th.start();
}
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 a BroadcastReceiver.
There I create a new Thread.
How can I show a toast in that thread?
Thanks
Use below code for perform UI operation from non-UI thread
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Try This code
public void start_insert() {
pDialog.show();
new Thread() {
#Override
public void run() {
int what = 0;
try {
// Do Something in Background
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
what = 1;
e.printStackTrace();
}
handler22.sendMessage(handler22.obtainMessage(what));
}
}.start();
}
private Handler handler22 = new Handler() {
#Override
public void handleMessage(Message msg) {
pDialog.dismiss();
Toast.makeText(getApplicationContext(), "SuccessFull",
10).show();
}
};
Activity_Name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// your stuff to update the UI
}
});
Use this code to update UI thread or execute any UI related operation.
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
So I am trying to create a "strobe" light effect in my app.
To do this I need a time delay, one of 100ms the other of 20.
Here is the code I'm using.
Thread timer = new Thread();
long longTime = 100;
long shortTime = 20;
for (int x = 0; x < 2000000; x++)
{
layout.setBackgroundColor(background);
try {
timer.sleep(longTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.setBackgroundColor(backgroundBlack);
try {
timer.sleep(shortTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The issue I have is that when I click the button to call that code, nothing happens. So I've done a bit of debugging and am pretty sure it is the timing call. I have never programmed in Java before so I am unsure how to call a Thread Sleep.
You could use a Handler as below to achieve this.
public class Strobe extends Activity {
private LinearLayout mLinearLayout;
private Handler mHander = new Handler();
private boolean mActive = false;
private boolean mSwap = true;
private final Runnable mRunnable = new Runnable() {
public void run() {
if (mActive) {
if (mSwap) {
mLinearLayout.setBackgroundColor(Color.WHITE);
mSwap = false;
mHander.postDelayed(mRunnable, 20);
} else {
mLinearLayout.setBackgroundColor(Color.BLACK);
mSwap = true;
mHander.postDelayed(mRunnable, 100);
}
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mLinearLayout = (LinearLayout) findViewById(R.id.strobe);
startStrobe();
}
private void startStrobe() {
mActive = true;
mHander.post(mRunnable);
}
}
Set a Theme to the Activity to make it full screen.
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
I think this article would benefit you.
http://oreilly.com/catalog/expjava/excerpt/index.html
specifically this
http://oreilly.com/catalog/expjava/excerpt/index.html#EXJ-CH-6-FIG-1
Your problem is that you are not running in the Thread. In order to run code in the thread you must override it's run() method. Based on your current code, the following may capture what you want to do.
Thread timer = new Thread(){
public void run(){
long longTime = 100;
long shortTime = 20;
for (int x = 0; x < 2000000; x++)
{
layout.setBackgroundColor(background);
try {
Thread.sleep(longTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
layout.setBackgroundColor(backgroundBlack);
try {
Thread.sleep(shortTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
timer.start();
However, threads don't play that well with the Android OS. For your application, it may be better to use Android services. See http://developer.android.com/guide/topics/fundamentals/services.html .