i want to do some stuff on every few seconds in my app, for that purpose , i have implemented HandlerThread & handler via following code
handlerThread = new HandlerThread(getClass().getSimpleName());
handlerThread.start();
handler = new Handler(handlerThread.getLooper(), new Callback() {
#Override
public boolean handleMessage(Message msg) {
//my code here
return l.this.handleMessage(msg);
}
});
I initiate this handler by sending message from onCreate()
I handle the message as follows :
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop==0)
{
checkLauncher();
sendMessage(MY_MESSAGE); // I Send the message from here to make //this continuous
}
}
return true;
}
It's Working fine but it Sends message too fast , i mean constantly , instead i want this message to be sent after 2 or 3 seconds , In Short , i want to repeat task every 2-3 seconds.
How can i do this on above code ? please some one help
First declare one global varialbe for Handler to update the UI control from Thread, like below:
Handler mHandler = new Handler();
Now create one Thread and use while loop to periodically perform the task using the sleep method of the thread.
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);// change the time according to your need
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// Write your code here to update the UI.
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
Else just add this in your code:
handler.postDelayed(new Runnable(){
public void run() {
// do something
}}, 20000);
Why not to use Handler.sendMessageDelayed? It allows you to schedule your message to be delivered to the Handler with delay that you specify. So your code will look like this:
private boolean handleMessage(Message msg) {
switch (msg.what) {
default:
return false;
case MY_MESSAGE:
if(handler_stop == 0) {
checkLauncher();
sendMessageDelayed(MY_MESSAGE, 2000); // Send message everytime with 2 seconds delay
}
}
return true;
}
hi i have an simple way for doing this
try this
Runnable runnable;
final Handler handler = new Handler();
runnable = new Runnable() {
public void run() {
// HERE I AM CHANGING BACKGROUND YOU CAN DO WHATEVER YOU WANT
_images[i].setBackgroundResource(imageArray[0]);
i++;
handler.postDelayed(this, 1000); // for interval...
}
};
handler.postDelayed(runnable, 1000); // for initial delay..
worked for me hope you will also find it working
thanks
Vote Up if find usefull.
Related
I need a delay for around 5 seconds. I have tried using Timer using below code :
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
Log.d(TAG,"Timer");
}
}, 4000, 5000);
When i check logs, the Timer is getting printed thrice. If I change time, sometimes it gets printed in log 4 times as well.
I have tried using Handler as well like below :
final Handler mHandler = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(10000);
mHandler.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
Log.d(Utility.TAG,"Sleep::");
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
But again the log is printing multiple times. I just want to call my method once not multiple times. How can I achieve it ?
EDIT
used handler without thread as well like below :
final Handler h = new Handler();
final int delay = 3000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
h.postDelayed(this, delay);
Log.d(Utility.TAG,"Sleep ::");
}
}, delay);
But again, Log is getting printed thrice
Your third approach (no Timer, no Thread) is the closest to being correct. It's printing multiple times because the Runnable is re-posting itself every time it runs. If you only want it to run once, remove this line from the run() method:
h.postDelayed(this, delay);
I have a code running inside the Thread. I tried to use the handler to do receive the message from the thread so i can update the UI. Unfortunately, the message didn't get send to the handler.
This is my code snippet inside the run method of the Thread
ChromaticLayout chromatic = new ChromaticLayout(mPartition, mDeviceWidth, mDeviceHeight, mData);
chromatic.execute(new ChromaticLayout.LayoutCallback() {
#Override
public synchronized void retrieveResult(Object[][] data) {
// TODO Auto-generated method stub
mPhotoData.clear();
Log.w("CALLBACK", "start");
for (int i=0; i<data.length; i++)
{
PhotoFrameData[] row = new PhotoFrameData[data[i].length];
for (int j=0; j<data[i].length; j++) {
if (j==0)
Log.w("CALLBACK", "Width = " + ((PhotoFrameData) data[i][j]).getRectangle().width() + " height = " + ((PhotoFrameData) data[i][j]).getRectangle().height() );
row[j] = (PhotoFrameData) data[i][j];
}
mPhotoData.add(row);
}
Log.w("CALLBACK", "end");
PhotoFrameAdapter.this.handle.post(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
PhotoFrameAdapter.this.handle.sendEmptyMessage(1);
} });
//if (!PhotoFrameAdapter.this.handle.sendEmptyMessage(1))
// Log.w("CALLBACK", "Handle not working");
}});
}
The is the receiving message of the handler:
protected Handler handle = new Handler() {
public void handleMessage(Bundle message) {
//PhotoFrameAdapter.this.notifyDataSetChanged();
mListener.dataLoaded(this);
}
};
What make it not adding to the message queue and call the handleMessage? Thanks
try this:
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
//do staff
break;
}
};
};
Another way you can use a Handler is as follows (it's perhaps a simpler implementation in many cases):
Define the hander on the UI thread:
private Handler mHandler = new Handler();
Then from your background thread just post a Runnable with the code you want to run:
mHandler.post(new Runnable() {
#Override
public void run() {
// Code to run here
}
});
I have a HandlerThread, to which I keep posting a runnable every 5 seconds. Something like this:
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
//...
handler.postDelayed(this, 5000);
}
});
I need to quit the looper at some point, after 60 seconds or something like that.. so I write:
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
thread.getLooper().quit();
}
}, 60000);
I think this causes the looper to quit abruptly, so I start getting this "warning" messages:
W/MessageQueue(3726): java.lang.RuntimeException: Handler
(android.os.Handler) {4823dbf8} sending message to a Handler on a dead
thread
I want to avoid this error msg, I thought that I could solve it by using the Looper.quitSafely() method.. but I checked the API and it's no longer available.
Does anyone know what happened to it? (It's not deprecated like some other methods).
Is there some way I can quit the looper safely? Thanks!
You could try to use a boolean to know if the code should be executed. Something like this:
private boolean runHandler = true;
...
HandlerThread thread = new HandlerThread("MyThread");
thread.start();
Handler handler = new Handler(thread.getLooper());
handler.post(new Runnable() {
public void run() {
if(runHandler){
//...
handler.postDelayed(this, 5000);
}
}
});
mainHandler = new Handler(Looper.myLooper()); //main thread's
mainHandler.postDelayed(new Runnable() {
#Override
public void run() {
runHandler = false;
}
}, 60000);
Im not Thread Guru, but this way can give you direction:
...
_thread.setRunning(true);
_thread.start();
..
public void stopThread(){
boolean retry = true;
_thread.setRunning(false);
while (retry) {
try {
_thread.join();
retry = false;
Log.e("test", "thread stopped");
} catch (InterruptedException e) {
Log.e("test", "can't stop thread, retrying...");
// we will try it again and again...
}
}
}
In your thread:
while (isRunning) {
//...
}
1st all you implement run method in loop (while(isRunnig){}).
On finish, you switch flag to false and "wait" for join.
I have implemeted a custom camera and I want it to go, after a period of time into a standby state. The standby concsists from a stopPreview, a camera release and a view that tells the user to tap in order to exit the standby. Because I set the text within the new thread, I get the CalledFromWrongThreadException, but I don't know what the solution could be. I found other posts around, but none of them really worked.
Code:
private void initCamera()
{//more code
threadModifiedText = (TextView) findViewById(R.id.textView1);
Thread standbyThread = new Thread()
{
#Override
public void run()
{
try
{
while (timeCounter > 0)
{
if (!activeThread)
{
sleep(100);
if (timeCounter % 10 == 0)
{
threadHandler.sendEmptyMessage((int) timeCounter / 10);
}
timeCounter--;
}
}
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
mCamera.stopPreview();
mCamera.release();
TextView standbytext = new TextView(SlicesActivity.this);
standbytext.setText("Tap to exit standby mode");
FrameLayout preview = (FrameLayout) findViewById(id.FrameLayout_camera_preview);
preview.addView(standbytext);
}
};
standbyThread.start();
//more code}
And
#Override
public void onUserInteraction()
{
Log.d("~~~~~~~~~", "apasat");
activeThread = true;
timerCounter = 300;
}
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
// whenever the Thread notifies this handler we have
// only this behavior
threadModifiedText.setText("\ncounter is " + Integer.toString(msg.what));
}
};
Please guys, give me some suggestions. 10x
try to use
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO: update your UI here
}
});
in your thread to update UI
You cannot set text values inside any thread except the UI thread. Complete your background thread operations and set the text value after your operations are over in the UI thread.
I need a thread (it does httppost ,and parse the answer xml and refresh listview to set the changes from parsed xml) in 3 sec interval
I have already tried this code
Timer timer = new Timer();
timer.scheduleAtFixedRate(
new TimerTask() {
public void run() {
try {
httpPostList(url);
saxParseList();
list.invalidateViews();
Thread.sleep(1000);
} catch (Exception ie) {
}
}
}, 1000, 1000 * 30);
I would appreciate you to create a Service with an AsyncTask in it.
Async Tasks are the Android Synonym to normal Java Tasks, Documentation finding here: http://developer.android.com/reference/android/os/AsyncTask.html
Services are Background Processes, seeing this Doc:
http://developer.android.com/reference/android/app/Service.html
Try using handlers:
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
// ...
handler = new Handler() {
#Override
public void handleMessage(Message msg) {
updateUI();
}
};
Thread thread = new Thread() {
#Override
public void run() {
while(true) {
Message msg = new Message();
handler.sendMessage(msg);
try {
sleep(3*1000); // 3 seconds
} catch (InterruptedException e) {
}
}
}
};
thread.start();
}
private synchronized void updateUI() {
// ...
}
Finally I made it using "Async task".