forever running thread + updating UI in android - android

Let's say I have a TextView and I want to update it's text with random numbers continuously, from the start of the application until it terminates.
What's the way to perform such a task? Does it have to be timed? (ie update it once in a second etc.) A statement with while(true) can't be used because there's only one UI thread in android and such a statement blocks it forever.
EDIT: Thanks for the quick and accurate answers. After seeing the answers and and thinking a little bit, I've come up with a tricky way to achieve this. Is there any downside of such a technique?
TextView tv;
Handler myHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView) findViewById(R.id.textView1);
myHandler=new Handler();
myHandler.post(new Nani());
}
private class Nani implements Runnable{
int i=0;
#Override
public void run() {
tv.setText(Integer.toString(i));
myHandler.post(this);
i++;
}
}
Simply, Runnable queues itself..

Without knowing more about what exactly you are doing such as when or why, you will want to use a Handler with postAtTime(). This part of the Docs talks more about how to handle these things depending on what you need

This can be achieved by using the Looper class: http://developer.android.com/reference/android/os/Looper.html
A good tutorial for using this, can be found here: http://pierrchen.blogspot.dk/2011/10/thread-looper-and-handler.html

This example approach with self-restarting CountDownTimer would do. Though this might be not the best approach, it will work
public class CountDown extends Activity {
TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
tv = new TextView(this);
this.setContentView(tv);
//5000 is the starting number (in milliseconds)
//1000 is the number to count down each time (in milliseconds)
MyCount counter = new MyCount(5000,1000);
counter.start();
}
public class MyCount extends CountDownTimer{
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
this.start();
}
#Override
public void onTick(long millisUntilFinished) {
tv.setText("your values here");
}
}
}

I think the best way is to use a Handler with timer. But make sure that you must not kill or terminate the runner when living one or other activities
e.g.:
private void timer() {
mRunnable = new HandlerManger();
mHandler = new Handler();
mHandler.postDelayed(mRunnable, 1000*10);
}
The runnable
private class HandlerManger implements Runnable {
#Override
public void run() {
// your business logic method here;
}
}
Activity
private Handler mHandler;
private Runnable mRunnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act...);
timer();
}

Related

How to close a window/activity after a certain amount of time

am writing an android application, it allow someone add two numbers and input the answer. but I want this numbers to display for only 5 seconds and then a new number show up, if they input the correct or wrong answer, the timer reset and display new numbers..
i have written the code that does the random numbers and other just the timer am unable to do
someone help please
Using a Handler and Runnable should work for you but don't use an Anonymous runnable as they can cause memory leaks. Instead extend runnable into a static class and use removeCallbacks in onDestroy.
Also you can use WeakReference as onDestroy is not guaranteed to be called so a WeakReference will allow GC to free up the memory if your activity gets killed
public class BarActivity extends AppCompatActivity {
private Handler mHandler;
private FooRunnable mRunnable;
private void finishActivityAfterDelay(int milliSeconds) {
mHandler = new Handler();
mRunnable = new FooRunnable(this);
mHandler.postDelayed(mRunnable, 5000); // 5 seconds
}
#Override
protected void onDestroy() {
mHandler.removeCallbacks(mRunnable);
super.onDestroy();
}
private static class FooRunnable implements Runnable {
private WeakReference<AppCompatActivity> mWeakActivity;
public FooRunnable(AppCompatActivity activity) {
mWeakActivity = new WeakReference<>(activity);
}
#Override
public void run() {
AppCompatActivity activity = mWeakActivity.get();
if (activity != null) activity.finish();
}
}
}
You can use android.os.Handler class to do so,
Like
private Handler handler = new Handler(); // Create Handler
Runnable runnable = new Runnable() {
#Override
public void run() {
// Perform action here...
}
};
handler.postDelayed(runnable, 3 * 1000); // action will be performed after 3 seconds.
CountDownTimer timer = new CountDownTimer(30000/*modify value as per need*/, 1000) {
public void onTick(long millisUntilFinished) {
//millisUntilFinised is the remaining time
}
public void onFinish() {
//timer finished .Do what you need to do next here
}
};
use timer.start();where you had to start the timer.

How to pause handler.postDelayed() timer on Android

How can i pause the handler.postDelayed() timer using a button. So when i click the same button again the handler.postDelayed() timer should resume.
handler.postDelayed(counterz, 60);
Handler does not have a timer to tweak. You are posting to event-queue of a thread, where a lot of other stuff is running as well.
You can cancel posted Runnable's:
handler.removeCallbacks(counterz);
And post again, to resume.
Handler does not have a pause method. You need to cancel and run again.
http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)
public final void removeCallbacks (Runnable r)
Remove any pending posts of Runnable r that are in the message queue.
When not required you need to call m_handler.removeCallbacks(m_handlerTask) to cancel the run. If you need again you need to run the the task again.
Handler m_handler;
Runnable m_handlerTask ;
m_handler = new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
// do something
m_handler.postDelayed(m_handlerTask, 1000);
}
};
m_handlerTask.run(); // call run
Suppose you use a timer. Even timer does not have pause method.
public class YourActivity extends AppCompatActivity {
private static boolean handlerflag=false;
private Handler handler;
private Runnable runnable;
private int myind=0,index=0,count=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_activtiy);
//oncreate exe only
handlerflag=true;
handler = new Handler();
startyourtime(0);
}
private void startyourtime(int a) {
myind=0;
for (index=a; index<10 ;index++) {
myind++;
runnable=new Runnable() {
count++;
#Override
public void run() {
//your code here
}
};handler.postDelayed(runnable, Constants.TIME_LIMIT * myind);
}
#Override
protected void onPause() {
super.onPause();
handlerflag=false;
handler.removeCallbacksAndMessages(null);
}
#Override
protected void onResume() {
super.onResume();
if(!handlerflag)
{
startyourtime(count);
}
}
}

Looper not called outside the Thread class

I am learning how to use Looper and Handler class in android development
http://developer.android.com/reference/android/os/Looper.html
The example given in the android development is not clear to understand what is the usage and the how to use it.I dont know how to add Handler inside the Looper and how I can call the Looper to loop.
If it is available, can anyone give me a simple example to use it.
public class LooperTest extends Activity{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
private class LooperTesting extends Thread
{
public Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handlerMessage(Message msg)
{
// do something
}
};
Looper.loop();
}
}
}
Hope this Links are helps to u
Link1
Link2
Link3
In your example you have only defined a Thread with a Looper. You need to start the Thread with the associated Looper before you can post any messages to it. I've added some code to your example to illustrate what has to be done:
public class LooperTest extends Activity{
LooperTesting mBgThread;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBgThread = new mBgThread();
// Start the thread. When started, it will wait for incoming messages.
// Use the post* or send* methods of your handler-reference.
mBgThread.start();
}
public void onDestroy() {
// Don't forget to quit the Looper, so that the
// thread can finish.
mBgThread.handler.getLooper().quit();
}
private class LooperTesting extends Thread
{
public Handler handler;
public void run()
{
Looper.prepare();
handler = new Handler()
{
public void handlerMessage(Message msg)
{
// do something
}
};
Looper.loop();
}
}
}

Timer and setContentView on Android

I want to execute a piece of code
So that users can pay attention to my LOGO
Like other APP
I want to use timer Execution setContentView.
Compiler is not wrong.
But execution error.
unfortunately has stopped.
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
abc();
}
public void abc() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
goToLayout1();
}
private void goToLayout1() {
setContentView(R.layout.activity_main2);
timer.cancel();
}
}, 1000, 2000);
}
}
I suggest you should have two activity.First activity is for showing splash screen.You can finish this after 3 seconds and start another activity that is activity with the layout actitiy_main2.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Runnable runnable=new Runnable(){
public void run(){
finish();
//start main activity
}
};
Handler handler=new Handler();
handler.postDelayed(runnable,3000);
}
you are attempting to modify the UI thread from a non-UI thread (a simple java timer)
so please, take care of it and read this Update UI from Thread. Then please, post the exception!

TimerTask doesn't take effect

Here's my code:
public class SomeName extends MapActivity implements OnClickListener, OnTouchListener{
public Timer t1 = new Timer();
public TimerTask tt;
public long interval = 5000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.map);
timer();
}
public final void timer()
{
t1 = new Timer();
tt = new TimerTask() {
#Override
public void run() {
systemClick();
}
};
t1.scheduleAtFixedRate(tt, 10000, interval);
}
public void systemClick()
{
Toast.makeText(getApplicationContext(),"System Button Clicked", 5).show();
}
Actually, I want to call some function, where I refresh my location.
But I can't understand why I never get the toast on the screen.
I'm new to android.
Thanks for any help.
use handler in your Activity
final Handler handlerforadd = new Handler();
Runnable runnableforadd = new Runnable() {
#Override
public void run() {
handlerforadd.postDelayed(this, 1000);
}
};
handlerforadd.postDelayed(runnableforadd, 0);
The reason is the Toast has to be done on the UI thread. In your current code the method run() is being executed on a separate thread. I would suggest looking at this article on Processes and Threads. #parag is correct using a Handler is one way to get a reference to the UI thread but there are other methods.

Categories

Resources