Android: Runonuithread Vs Asynctask

Android: RunOnUiThread vs AsyncTask

When you use new Thread you're really creating a new thread every time you execute that. AsyncTask however, uses a static pool of max 128 threads and will reuse an old thread whenever it exists. So, running AsyncTask 10 times in serial will only create one thread that runs the task 10 times instead of 10 threads.

That's one of the differences among many.

AsyncTask vs Activity.runOnUiThread() vs Handler.post()

They are all really a Handler either visibly or internally.

AsyncTask#finish() that calls onPostExecute() is called from a Handler message loop.

runOnUiThread() posts the Runnable to a Handler if the current thread is not the UI thread. If it is the UI thread, the runnable is executed synchronously - this is not always desirable.

Directly using a Handler gives you low level control and only that.

What to use depends on your specific requirements.

Android Asynctask and runOnUiThread

I think you are using AsyncTasks in a very bad way. You want to execute a Runnable on an asynchronous thread and then you call runOnUiThread inside of it to process a result on the UI thread. Why not using AsyncTasks in the way they are meant to be used?

Create a new task and use its common methods: doInBackground, onProgressUpdate, onPostExecute. If the AsyncTask is executed on the main thread these last two are already called on the UI thread.

new AsyncTask<Void, Void, Results>() {
@Override
protected Results doInBackground(Void... params) {
String result = OpenALPR.Factory.create(MainActivity.this, ANDROID_DATA_DIR).recognizeWithCountryRegionNConfig("us", "", destination.getAbsolutePath(), openAlprConfFile, 10);

Log.d("OPEN ALPR", result);

Results results = new Gson().fromJson(result, Results.class);
if (results != null || results.getResults() != null || results.getResults().size() > 0)
Log.d("ShowTheResults", results.getResults().get(0).getPlate());

return results;
}

@Override
protected void onPostExecute(Results result) {
if (results == null || results.getResults() == null || results.getResults().size() == 0) {
Toast.makeText(MainActivity.this, "It was not possible to detect the licence plate.", Toast.LENGTH_LONG).show();
resultTextView.setText("It was not possible to detect the licence plate.");
} else {
resultTextView.setText("Plate: " + results.getResults().get(0).getPlate()
// Trim confidence to two decimal places
+ " Confidence: " + String.format("%.2f", results.getResults().get(0).getConfidence()) + "%"
// Convert processing time to seconds and trim to two decimal places
+ " Processing time: " + String.format("%.2f", ((results.getProcessingTimeMs() / 1000.0) % 60)) + " seconds");
}
}
}.execute();

runOnUiThread is not running in AsyncTask

Try this way :

First create one Handler :

Handler mHandler = new Handler();

Change this,

public void commentBuilder()
{
runOnUiThread(new Runnable() // while debugging, it comes here, on Step Over it stick for 2 times and then move at the end of method without error
{
public void run()
{
// update UI code
}
});
}

With,

public void commentBuilder()
{
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
while (isRunning) {
try {
// Thread.sleep(10000);
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();
}

Stop thread by this once you are done with UI,

isRunning = false;

EDIT :

Try to Use Async Task in this way :

class parseComments extends AsyncTask<String, Integer,String> 
{
protected String doInBackground(String... params) {
String parseComReturn = parseComments();
return parseComReturn;
}

protected void onPostExecute(String result) {
if(result.equals("end"))
{
commentBuilder();
}
}
}

Thanks.

I want to run an AsyncTask on UI thread - how can I do that?

You definitively could, but as @Devrath said, it is pointless. AsyncTask are used for background operation.

Here is a sample that uses the runOnUiThread method:

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

@Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
@Override
public void run() {
// WORK on UI thread here
}
});
return null;
}

@Override
protected void onPostExecute(Void result) {
}

@Override
protected void onPreExecute() {}

@Override
protected void onProgressUpdate(Void... values) {}
}

Is using runOnUiThread inside AsyncTask inefficient and bad?

Yes, use-cases like this are a big reason why the runOnUiThread() method exists in the first place. The idea is you allow your background thread(s)/AsyncTask instance(s) to run your lengthy operations in the background, and then provide a simple hook that they can use to update the interface when they have the result (or at arbitrary intervals, as different pieces of the result become available).

As long as that's what you're doing, then your usage is fine. What you want to avoid doing is performing a lengthy operation on the main thread, either directly or indirectly by passing in some lengthy operation from a background thread.

Of course you don't have to do it that way if you don't want to. You could use postExecute() instead. Or you could store the result somewhere and then use any sort of message-passing API to notify the main thread that the result is ready, and so on.

Converting runOnUiThread to AsyncTask

This is awkward. I asked a question and am answering it myself :/
Actually I was trying AsyncTask(Object, Void, Cursor) and it was not doing me any good.

Here is the class which is working:

class autoComplete extends AsyncTask<Void, Void, Void> {
final DataBaseHelper dbHelper = new DataBaseHelper(ActivityName.this);

@Override
protected Void doInBackground(Void... params) {

dbHelper.openDataBase();
item_list = dbHelper.getAllItemNames();
return null;
}

@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ArrayAdapter<String> sAdapter = new ArrayAdapter<String>(
ClassName.this, android.R.layout.simple_dropdown_item_1line,
item_list);
itemNameAct= (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView_item_name);
itemNameAct.setAdapter(sAdapter);
}

}

and then in onCreate i initialize it as:

new autoComplete().execute();

Android - Difference between Thread and AsyncTask?

When you use a Thread, you have to update the result on the main thread using the runOnUiThread() method, while an AsyncTask has the onPostExecute() method which automatically executes on the main thread after doInBackground() returns.

While there is no significant difference between these two in terms of "which is more beneficial", I think that the AsyncTask abstraction was devised so that a programmer doesn't have to synchronize the UI & worker threads. When using a Thread, it may not always be as simple as calling runOnUiThread(); it can get very tricky very fast. So if I were you, I'd stick to using AsyncTask and keep Thread for more specialized situations.



Related Topics



Leave a reply



Submit