i try to make my screen blinking like this:
for (int i=0;i<10;i++)
{
targetView.setBackgroundColor(Color.BLUE);
for (int j=0;j<500;j++); //delay
targetView.setBackgroundColor(Color.RED);
}
but it wont work
Try this,
targetView.setBackgroundColor(Color.BLUE);
try {
Thread.sleep(5000); // milliseconds to wait...
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
targetView.setBackgroundColor(Color.RED);
EDIT
public class TSActivity extends Activity {
LinearLayout lin;
private int finalStatus = 0;
private Handler colorHandler = new Handler();
boolean flag = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lin = (LinearLayout)findViewById(R.id.linMain);
new Thread(new Runnable() {
public void run() {
while (finalStatus < 100) {
// process some tasks
finalStatus = doSomeTasks();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the color
colorHandler.post(new Runnable() {
public void run() {
if(flag)
{
lin.setBackgroundColor(Color.BLUE);
flag = false;
}
else
{
lin.setBackgroundColor(Color.GREEN);
flag = true;
}
}
});
}
}
}).start();
}
// color changer simulator... a really simple
public int doSomeTasks() {
long fileSize = 0;
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}
// ...add your own
}
return 100;
}
}
Hope this will help you..
Thanks...
You can use handler also.
Runnable r=new Runnable(){
public void run(){
if(red){
targetView.setBackgroundColor(Color.RED);
red=false;
}
else{
targetView.setBackgroundColor(Color.BLUE);
red=true;
}
if(!stop_blinking) handler.postDelayed(this,1000);
}
};
handler=new Handler();
handler.postDelayed(r,1000); //1000 is in mili secs.
stop_blinking is boolean which you need to set whenever you want the view to stop blinking.
Related
I am using IVideon Player and I have an URL which I want to play. Things are okay but I am unable to handle Seekbar status. I am getting 0 when I want to get time how much my video has been played. Please help me out. What I did is here
class SeekBarProgress implements Runnable {
#Override
public void run() {
int totalDuration = event_list.get(counter).getDuration();
for (int i = 0; i <= totalDuration; i++) {
if (isPlaying) {
final int value = i;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mTimeUpdateHandler.post(new Runnable() {
#Override
public void run() {
strttime.setText(Utils.getDuration(Utils.getLong((double) value))); // the TextView Reference
mBufferBar.setProgress(value);
}
});
}
}
}
}
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 have made an android app in that i have implemented play pause function,But I only knows about play ,I don't know how to stop sliding on the same button click,I have used two functions for it as below,play is working but pause is not.!
onClick
if (!flag) {
play();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.pause);
flag = true;
} else {
pause();
new Thread(ViewPagerVisibleScroll).start();
ivPlay.setBackgroundResource(R.drawable.play_btn);
flag = false;
}
play and pause
void play() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 3000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
void pause() {
pos = viewPager.getCurrentItem();
ViewPagerVisibleScroll = new Runnable() {
#Override
public void run() {
try {
if (pos <= adapter.getCount() - 1) {
viewPager.setCurrentItem(pos, true);
viewPager.setScrollDurationFactor(6);
handler.postDelayed(this, 300000);
pos++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
in pause button click :
handler.removeCallbacksAndMessages(ViewPagerVisibleScroll);
Try this
public class MainActivity extends Activity implements Runnable{
private int progressBarStatus = 0;
private Handler progressBarHandler = new Handler();
ProgressBar linProgressBar;
private long fileSize = 0;
Thread t1;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
b2.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
linProgressBar.setProgress(0);
t1.interrupt();
}
});
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
basicInitializations();
}
});
}
public void basicInitializations(){
linProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
linProgressBar.setProgress(0);
linProgressBar.setMax(100);
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100) {
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
}
public int doSomeTasks() {
while (fileSize <= 1000000) {
fileSize++;
if (fileSize == 100000) {
return 10;
} else if (fileSize == 200000) {
return 20;
} else if (fileSize == 300000) {
return 30;
}else if (fileSize == 400000) {
return 40;
}else if (fileSize == 500000) {
return 50;
}
}
return 100;
}
#Override
public void run() {
// TODO Auto-generated method stub
}
}
this is my main code and i could not stop this thread .
i want to stop it when i click the button b2(say cancel button).
the above code is not the original code and is a model , so please tell me how to stop that thread .
thankyou in advance . . . .
I have a alternate answer can try the same, inside your runnable loop always check a flag as run_flag, create it as a member variable and set it as true once you stared the loop, you can make it run_flag as false wenever you are done and at the same time you can set null to your thread also ... a safer way to come out through runnable loop and thread.
try{
t1 = new Thread()
{
public void run() {
while (progressBarStatus < 100 && run_flag == true) { // added run_flag here
// process some tasks
progressBarStatus = doSomeTasks();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Update the progress bar
progressBarHandler.post(new Runnable() {
public void run() {
linProgressBar.setProgress(progressBarStatus);
}
});
}
if (progressBarStatus >= 100) {
try {
Thread.sleep(2000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
};
t1.start();
}catch (Exception e) {
}
Your thread spends most of its time in Thread.sleep(), which is helpful. The thread pointer, t1, is a class member, which is also helpful. From your button handler, you can check to see if t1 is still alive and, if so, call t1.interrupt();. This will cause the thread's current sleep and future sleeps to throw the InterruptedException... now you just need to modify your exception handler to quit the thread in that case.
I am trying to update two TextViews txtName and textEndName. When i debug sometimes it updates the text but rest of the time it does not works. Sometime it works but not not exactly what it is suppose to.What is the problem in the below given code ?
txtName = (TextView) findViewById(R.id.txtstarttag);
textEndName = (TextView) findViewById(R.id.txtendtag);
startSec = (TextView) findViewById(R.id.txtstartsecnd);
endSec = (TextView) findViewById(R.id.txtendsecnd);
btnplay = (ImageButton) findViewById(R.id.btnplay);
btnback = (Button) findViewById(R.id.btnback);
btnback.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
((MyMixes) getParent()).goBack();
}
});
btnplay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
btnClick();
}
});
splitArray();
Thread t = new Thread()
{
public void run()
{
while (isDownloading)
{
if (Data.filenames != null && Data.filenames.size() >= (getIntent() .getExtras().getInt("index") + 1) && Data.filenames.get(getIntent().getExtras() .getInt("index")) != null)
{
try
{
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(Data.filenames.get(getIntent().getExtras().getInt("index")));
mediaPlayer.prepare();
mediaPlayer.start();
Timer t = new Timer();
handler.postDelayed(onEverySecond, 1000);
mediaPlayer.setOnCompletionListener(new OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp) {
mediaPlayer.seekTo(0);
}
});
boolean isPlaying = mediaPlayer.isPlaying();
if(!isPlaying){
mediaPlayer.pause();
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
isDownloading = false;
}
}
}
}
};
t.start();
}
private Runnable onEverySecond=new Runnable()
{
public void run()
{
if (mediaPlayer.isPlaying())
{
for (int i = index; i < intervals.length; i++)
{
if (i != index && mediaPlayer.getCurrentPosition() > intervals[i])
{
index = i;
handler.dispatchMessage(handler.obtainMessage());
handler.postDelayed(onEverySecond, 1000);
break;
}
}
}
}
};
Handler handler = new Handler()
{
#Override
public void handleMessage(Message msg) {
txtName.setText(arrName.get(index));
textEndName.setText(arrName.get(index+1));
super.handleMessage(msg);
}
};
public void splitArray()
{
strSplit = kggg.split("\n");// string array
intervals = new long[strSplit.length];
Time timer;
for (int j = 0; j < strSplit.length; j++)
{
split = strSplit[j];// string
split1 = split.split("-");// string array
arrName.add(split1[0]);
String timeq = split1[1];
String[] timed = timeq.split(":");
if(timed.length == 3)
{
timer = new Time(Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()), Integer.parseInt(timed[2].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 2)
{
timer = new Time(0, Integer.parseInt(timed[0].trim()), Integer.parseInt(timed[1].trim()));
intervals[j] = timer.getTime();
}
else if(timed.length == 1)
{
timer = new Time(0, 0, Integer.parseInt(timed[0].trim()));
intervals[j] = timer.getTime();
}
}
for (int j = intervals.length-1; j >= 0 ; j--)
{
intervals[j] = intervals[j] - intervals[0];
}
}
public void btnClick()
{
k++;
k = k % 2;
startSong(k);
}
private void startSong(int i) {
if (i == 1) {
System.out.println("11111" + i);
btnplay.setImageResource(R.drawable.pause);
try {
System.out.println("start try chech------");
mediaPlayer.start();
} catch (Exception e) {
mediaPlayer.pause();
}
}
if (i == 0) {
btnplay.setImageResource(R.drawable.play);
mediaPlayer.pause();
System.out.println("00000" + i);
}
}
You shouldn't be doing this:
handler.dispatchMessage(handler.obtainMessage());
Try this instead:
handler.sendMessage(handler.obtainMessage());
EDIT: Added other things I noticed
I also see that in your Thread you have a loop while (isDownloading) and you set isDownloading to false in the finally block. This loop while never run more than once.
Also, you do
btnplay.setImageResource(R.drawable.play);
inside a thead. This isn't good. You need to do everything related to UI on the main (UI) thread.