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

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();
}
}

Related

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

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!");
}
}

How to stop the thread in Android?

I have a thread in my callback function as follows:
#Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something
}
}, 2000);
}
});
}
I will to close the the above thread when I press the back button or onDestroy. How can I do it. Thank you
#Override
public void onBackPressed() {
// Close or distroy the thread
}
#Override
public void onDestroy() {
// Close or distroy the thread
}
Please do this like
private Handler handler;
private Runnable runnable;
#Override
public void onConnectError(final BluetoothDevice device, String message) {
Log.d("TAG","Trying again in 3 sec.");
runOnUiThread(new Runnable() {
#Override
public void run() {
handler = new Handler();
runnable = new Runnable() {
#Override
public void run() {
//Do something
}
};
handler.postDelayed(runnable, 2000);
}
});
}
and
#Override
public void onBackPressed() {
if (handler != null && runnable != null) {
handler.removeCallbacks(runnable);
}
}
and same in onDestroy();
I'm mostly use thread in this way.See its independent in activity
public class TestActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.abc);
holdConnectionHandler.sendEmptyMessage(0);
}
Handler holdConnectionHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
// do some work
holdConnectionHandler.sendEmptyMessageDelayed(0, 10 * 1000);
}
};
#Override
public void onDestroy() {
super.onDestroy();
holdConnectionHandler.removeCallbacksAndMessages(null);
// or
holdConnectionHandler.removeMessages(0);
}
}
Thanks hope this will help you

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

Start AsyncTask in TimerTask

I have a timer that I want to start an AsyncTask when the countdown is done. If I put the execution of it in a handler it loops it and starts it many times. And if I dont put it in a Handler I get the following crash:
can't create handler inside thread that has not called looper.prepare()
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
private Handler mHandler = new Handler(Looper.getMainLooper());
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}
Any suggestions of how I can solve this?
AsyncTask is supposed to run on UI thread only. In your case, seems like you are not running it properly on a UI thread.
Perhaps try it like this:
timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
class ListUpdate extends TimerTask {
Looper looper = Looper.getMainLooper();
looper.prepareMainLooper();
private Handler mHandler = new Handler(looper);
public void run() {
mHandler.post(new Runnable() {
public void run() {
AsyncTask<Integer, Void, Boolean> task = new updateList();
task.execute();
}
});
}
}
By adding a handler outside of the TimerTask which I call from the TimerTask I could make it work!
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
RelativeLayout rl_header = (RelativeLayout)findViewById(R.id.rl_header);
Desktop desktop = helper.getDesktop();
try {
desktop.inflate(ll, rl_header, banners, DesktopApp.this);
Collections.sort(helper.nextListUpdate);
helper.nextListUpdate.remove(0);
timer = new Timer();
if (helper.nextListUpdate.size() > 0) timer.schedule(new ListUpdate(), helper.nextListUpdate.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
};
class ListUpdate extends TimerTask {
public void run() {
DesktopApp.this.runOnUiThread(new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(0);
}
});
}
}

Categories

Resources