I want to show a fragment for 5 seconds and then close it without the user interaction. This is my code.
#Override
public void onResume() {
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
listener.closeFragment(null);
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).run();
}
the listener.closeFragment(null);method works well (it close the fragment) but the fragment is never shown. Its like the thread runs before the fragment is visible. Any idea? is it posible?
Shouldn't you be using .start() instead of .run()?
You are just calling that that thread's logic sequentially.
Hope it helps.
Related
I want to save data to DB in new Thread and after that show toast on the UI.
Method for saving:
public void addToBasket(String text) {
new Thread(() -> {
//emulate save
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
//after that I need say ti UI thread - show Toast!
}).start();
}
I call this method:
BasketService.me().addToBasket(result.getContents());
I do now want use AsyncTask for this. Please tell me the best way to implement such tasks
batter to use:
runOnUiThread(new Runnable() {
public void run() {
//Do what ever you want do man
}
});
runOnUiThread() method to manipulate your UserInterface from background threads.
In case of callback from a nonUi thread to Ui thread you can use runOnUiThread()(As specified above) or Handler. Below is a example of using handler.
protected static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
protected void onSuccessInMainThread(final R result, final Bundle bundle) {
mainThreadHandler.post(new Runnable() {
#Override
public void run() {
callback.onSuccess(result, bundle);
}
});
}
protected void onErrorInMainThread(final Exception error) {
mainThreadHandler.post(new Runnable() {
#Override
public void run() {
callback.onError(error);
}
});
}
I would like to set an EditText with a timer thanks to CountDownTimer.
My EditText write second by second the number 3 and 2 but for the 1 there is a lag (it take 1,5 to 2 seconds).
Maybe I do it wrong.
This is my code :
CountDownTimer mCountDownTimer = new CountDownTimer(4000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
txt_timer.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish() {
txt_timer.setText("GO");
}
};
mCountDownTimer.start();
That is because the UI thread is doing too much work. Try running a new thread on the UI thread itself:
runOnUiThread(new Runnable() {
public void run()
{
//Insert your code
}
});
}
Let me know if you can;t get this to work!
The memory in the device cause the problem. I found a solution running a new thread.
I have to declare int i=4; before and use this code :
new Thread() {
public void run() {
while (i-- > 1) {
try {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txt_timer.setText(String.valueOf(i));
}
});
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
txt_timer.setText("GO");
}
}.start();
I want to add and clear window flag inside a thread but not working. Basically i want my thread to keep the screen on for two seconds and then clear the screen on flag.
Here's my code:
public class WriteCommThread extends Thread {
private long time=2000;
public WriteCommThread(float count) {
time = (long) count;
}
public void run() {
while(connectionUnAbort==true){
// Lock screen
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
slleep();
//Unlock screen
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
connectionUnAbort=false;
}
}
public void slleep(){
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I solved it after doing research, i am posting the referred link.
Answer Link
Here's my solution to my problem and it worked perfectly. I added these runnable classes in my background thread (run method). And after sleeping i could clear the flag to keep the screen on.
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
MainActivity.this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
runOnUiThread(new Runnable() {
public void run() {
//stuff that updates ui
MainActivity.this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
});
I am trying to make a clock, using a TextView :)
Someone here told me that I couldn't use normal threads to change the UI, but Handler or AsyncTask. I managed to get it working a few days ago, but was not a consistent thread.
Now what I want is a consistent thread that is always changing the text of my Textview. I tried using this, but didn't work, any help?
private void startClock() {
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
while (true) {
final long millis = System.currentTimeMillis() - MainActivity.startedAt;
clock.setText("" + millis);
runOnUiThread (new Runnable() {
#Override
public void run() {
clock.setText("" + millis);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 2000);
}
you should get rid of:
while(true) {
....
sleep(1000);
...
}
because this get your thread stuck forever. your program should work like this:
private Handler mHandler = new Handler();
#Override
public void onResume() {
super.onResume();
mHandler.removeCallbacks(mUpdateClockTask);
mHandler.postDelayed(mUpdateCLockTask, 100);
}
#Override
public void onPause() {
super.onPause();
mHandler.removeCallbacks(mUpdateClockTask);
}
private Runnable mUpdateClockTask = new Runnable() {
public void run() {
updateClock();
mHandler.postDelayed(mUpdateClockTask, 2000);
}
};
and inside updateClock() you do all your UI updates.
Look here for an example https://stackoverflow.com/a/11140429/808940
Also note that you have a duplicate line in your code:
clock.setText(""+millis);
It appears both in the runOnUiThread and in the main handler, it should only appear in the runOnUiThread runnable
I am using handler.postDelayed method to create some delay for some animation stuff.
With that i am playing some song as well using Mediaplayer. User can exit this action class by clicking next. But on next screen the same song is continuing even though i called stop method in the next button's onclicklistener.
Is it due to the timedelay that is added which gets executed after the next activity is loaded. Any idea?
handler.postDelayed(new Runnable() {
public void run() {
mp = MediaPlayer.create(getApplicationContext(), R.raw.num2);
mp.start();
imageView1.setImageResource(R.drawable.countcat2);
}
}, 2000);
Did you add a Log to see if run() gets called? I would assume that your handler gets unregistered; after all, postDelayed will wait until the looper kicks in again.
I assume your animation is faster than those 2000ms? You wouldn't be able to have your handler called anyway after your activity is gone, it's accessing imageView1 which I presume is destroyed in onDestroy.
You could consider adding a flag that will force the operation to be called immediately in onDestroy, and/or you could use a Timer. In case of the timer, be sure to not use something like imageView1 after it has been destroyed.
Use threads. And then stop it with an interruption:
Public Thread getThread(final Handler handle, int delay)
{
return new Thread()
{
#Override
public void run()
{
try
{
synchronized(this)
{
Thread.sleep(delay);
handle.post(new Runnable()
{
#Override
public void run()
{
"the code to be exec."
}
});
}
}
catch(Exception e)
{
e.printStackTrace();
}
};
};
}
Or you can use use the postDelayed function
Public Thread getThread(final Handler handle, int delay)
{
return new Thread()
{
#Override
public void run()
{
try
{
synchronized(this)
{
handle.postDelayed(new Runnable()
{
#Override
public void run()
{
"the code to be exec."
}
}, delay);
}
}
catch(Exception e)
{
e.printStackTrace();
}
};
};
}
you will find that there's a little difference between this two methods. To interrupt it, do something like this:
Thread t = getThread(handle, delay);
t.start();
if(t != null)
{
if (t.isAlive())
{
t.interrupt();
}
}
Hope I have helped.