Why override method run() in subclass of HandlerThread doesn't execute completely? - android

I am new to Handler in Android, I wanna test Handler, so I use ThreadHandler and extends it, at the same time I override the method - run(), adding some log to indicate the start an end of the Looper. but when the test done, I just saw the start log and didn't see any end log, so why the override method run() didn't execute completely?
The code as following:
private void test_ThreadHandler(HandlerThreadTest handlerThreadTest){
handlerThreadTest.getHandler().post(new Runnable() {
#Override
public void run() {
Log.d(Tag, "handlerThreadTest quit!");
handlerThreadTest.quitSafely();
}
});
}
static class HandlerThreadTest extends android.os.HandlerThread {
private Handler mHandler;
public HandlerThreadTest(String name) {
super(name);
mHandler = new Handler();
}
public HandlerThreadTest(String name, int priority) {
super(name, priority);
mHandler = new Handler();
}
public Handler getHandler() {
return mHandler;
}
#Override
public synchronized void run() {
// I just see this log
Log.d(Tag, "Looper start!");
super.run();
// why I can't see this log ?
Log.d(Tag, "Looper end!");
}
}

Related

Remove callback not working in Handler

I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
myFunction(position);
handler.postDelayed(runnable,10000);
}
};
public void myFunction(int position)
{
if(position>10)
handler.removeCallbacks(runnable);
}
I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?
The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one. There are plenty of ways to refactor this. For example:
handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {
#Override
public void run() {
boolean reschedule = myFunction(position);
if(reschedule) {
handler.postDelayed(runnable,10000);
}
}
};
public boolean myFunction(int position)
{
if(position>10) {
return false;
}
return true;
}
You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.
You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()
#Override
public void run() {
handler.postDelayed(runnable,10000);
myFunction(position);
}

android implements runnable not working?

this is a simple code to understand the runnable .I tried but not working . can you guys help me pls this is my code
public class Autostart extends activity implements Runnable {
#override
public void run (){
System.out.println ("message");
}
}
}
this not printing any statements
If you are using an Activity, you need to write your code inside Activity lifecycle methods. onCreate() is called when the Activity is created. So starting your Runnable here would be the correct way to do it.
#Override
public void onCreate(Bundle savedInstanceState) {
Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
System.out.println ("message");
}
};
handler.postDelayed(r, 1000);
}
You have to create a Thread object and call start() using that object.
Thread t = new Thread(this);
t.start();
Or Just use Handler
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// Do Something here
}
}, 5000);
You can use below code to print a value after regular interval of time
public void callAsynchronousTask() {
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
Log.e("on print timee", your value);
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); // will execute after 1 sec
}
Hope this will help you
I found a similar solution to Swayam (android implements runnable not working?), however another handler.postDelayed reference within run() was required;
public void onCreate(
...
final Handler handler = new Handler();
final Runnable r = new Runnable()
{
public void run()
{
Log.i(TAG, "message");
handler.postDelayed(this, 1000);
...
}
};
handler.postDelayed(r, 1000);
Try following code
Handler mainThreadhandler = new Handler(getMainLooper());
mainThreadhandler.post(new Runnable(){
public void run(){
// UI work
}
});
public class Autostart extends activity implements Runnable {
Thread = thread;
#override
public void onCreate() {
thread = new Thread(this);
thread.start();
}
#override
public void run (){
System.out.println ("message");
}
}

How update the UI from another thread in Android?

I searched for a way to update UI from another thread, and found that the available approach is to use Handler.post(Runnable) as shown in the code snippet below:
public class MyClass extends Activity {
private final Handler myHandler = new Handler();
final Runnable updateRunnable = new Runnable() {
public void run() {
// Update UI
}
};
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
myHandler.post(updateRunnable);
}).start();
}
};
}
Instead can't we use Handler.sendMessage and do the UI updates from main UI thread in handleMessage():
public class MyClass extends Activity {
private final Handler myHandler = new Handler();
private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch(msg.what) {
// Do logic here
}
}
};
private OnClickListener buttonListener = new OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
myHandler.sendEmptyMessage(0);
}).start();
}
};
}
I'm sorry if this is a very basic question, however I'm quite confused with the above two approaches.
You need to use runOnUiThread. You can post a runnable which does the UI operation to main thread as follows,
public class Utils {
public static void runOnUiThread(Runnable runnable){
final Handler UIHandler = new Handler(Looper.getMainLooper());
UIHandler .post(runnable);
}
}
Utils.runOnUiThread(new Runnable() {
#Override
public void run() {
// UI updation related code.
}
});
Read more at:
android: update UI from another thread in another class
Updating UI / runOnUiThread / final variables: How to write lean code that does UI updating when called from another Thread
https://developer.android.com/training/multiple-threads/communicate-ui.html

Using Android Looper still throwing "Can't create handler inside..."

I have a looper and handler:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
updateUI(message.obj);
}
};
Looper.loop();
}
}
In my MainActivity I then call:
new LooperThread().start();
new Thread(new WorkerTask()).start();
Where WorkerTask implements Runnable.
Can't create handler inside thread that has not called Looper.prepare().
Inside my workerTask it is throwing the error on the second line:
locationManager = (LocationManager) activity.getSystemService(activity.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
If this is in Activity or fragment you can simply use runOnUiThread to update ui.
You need to use this:
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
Or to use it with your existing code:
private Handler handler;
public class LooperThread extends Thread
{
#Override
public void run()
{
Looper.prepare();
handler = new Handler()
{
#Override
public void handleMessage(Message message)
{
activity.runOnUiThread(new Runnable() {
public void run() {
updateUI(message.obj);
}
});
}
};
Looper.loop();
}
}

Using HandlerThread and Handler on a separate thread freezes UI thread

In my project, I want to implement a timer in another thread that counts down the time spent executing a certain method in my application, and do something if it is taking too much time. When executing the MyManager.startCommand() method, the application is freezing and I don't know why since I think I am not doing anything on the UI thread. Is there anything wrong with my code?
I had originally asked this question and was not experiencing an app freeze, so I don't think it's because I'm sleeping the thread: Runnable posted in another runnable not executed.
public class MyManager{
private MyManager sInstance;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mTimeoutTimer;
public static MyManager getInstance(){
if(sInstance == null){
sInstance = new MyManager();
}
return sInstance;
}
private MyManager(){
mHandlerThread = new HandlerThread("mHandlerThread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mTimeoutTimer = new Runnable() {
#Override
public void run() {
Log.e(“RUNNABLE RUNNING!”);
}
};
public class MyCommand {
private Runnable myRun;
public MyCommand(){
myRun = new Runnable() {
#Override
public void run() {
MyManager.getInstance().startTimeoutTimer();
MyCommand.this.run();
}
};
}
public void execute() {
myRun.run();
}
abstract public void run();
}
private void startTimeoutTimer(){
mHandler.post();
}
public void startCommand(){
new MyCommand().execute();
}
}
And how I'm using a MyCommand object:
MyCommand command =
new MyCommand() {
#Override
public void run() {
//make api call that happens in another thread
}
};
So I am basically trying to create the timeout timer for that API call.
Try this:
Just wrap your first runnable in a Thread.
public class MyManager{
private MyManager sInstance;
private HandlerThread mHandlerThread;
private Handler mHandler;
private Runnable mTimeoutTimer;
public static MyManager getInstance(){
if(sInstance == null){
sInstance = new MyManager();
}
return sInstance;
}
private MyManager(){
mHandlerThread = new HandlerThread();
mHandler = new Handler(mHandlerThread.getLooper());
mTimeoutTimer = new Runnable() {
#Override
public void run() {
Log.e(“RUNNABLE RUNNING!”);
}
};
public class MyCommand {
private Thread th;
private Runnable myRun;
public MyCommand(){
myRun = new Runnable() {
#Override
public void run() {
MyManager.getInstance().startTimeoutTimer();
try {
Thread.sleep(COMMAND_TIMEOUT_MILLIS * 3);
} catch (InterruptedException e) {}
MyCommand.this.execute();
}
};
th = new Thread(myRun);
}
public void execute() {
th.start();
mHandler.postDelayed(mTimeoutTimer);
}
}
private void startTimeoutTimer(){
mHandlerThread.start();
mHandler.postDelayed(mTimeoutTimer);
}
public void startCommand(){
new MyCommand().execute();
}
}
Also you forgot to start the mHandlerThread
private void startTimeoutTimer(){
mHandlerThread.start();
mHandler.postDelayed(mTimeoutTimer);
}

Categories

Resources