My Professional Android 4 Application Development book states, "Toasts must be created and shown on the GUI thread; otherwise, you risk throwing a cross-thread exception."
Use UI thread to display toast messages?
-
19-07-2023 - |
Question
I have a listener that is getting updates from a separate process. (I'm using IPC.)
Log.i("Test1", Thread.currentThread().toString()); // Thread[Binder_3,5,main]
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("Test2", Thread.currentThread().toString()); // Thread[main,5,main]
switch (taskId) {
case Constants.DOWNLOAD_TASK_EXECUTED: {
long time = prefs.getLong(Constants.LAST_UPDATED_KEY, System.currentTimeMillis());
String msg = Utils.getLastUpdatedString(res, time, Locale.getDefault(), false);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
case Constants.DELETED_TASK_EXECUTED: {
String msg = res.getString(R.string.delete_success);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
break;
}
}
}
});
Is it necessary to call the runOnUiThread
method and pass in a Runnable
to display toast messages when I get updates? Or is it okay to just display them in the same thread (Binder_3)? I'm not modifying anything in the UI.
Solution 2
OTHER TIPS
Tost Or Log Work in thread or other processes (but it's better to NOT Risk ! ) but Changing the UI must always Run in UI thread as you told with runOnUiThread
or using handler
Handler handler = new Handler();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow