Reputation: 30304
I'm working on Android UI Thread, and there is one time-consuming work, so I put It on another thread. There two thing I want:
1) after this sub-thread run, UI Thread will start to do workA
2)this workA will take some data that create in sub-thread.
Here my solution:
Car car;
public void onResume(){
super.onResume();
Thread t = new Thread(){
car = new Car();
car.takePetrol; //take car full petrol
}
});
t.join();
count_How_far_Car_can_go(car.getPetrol);
}
The problem in my code is: I have use t.join(); to wait thread t finish. And this will "Block" the UI Thread. Of course, that is not what I want. (because I make another thread so UI Thread still can work smoothly)
Who has another solution for my problem, please help me :)
thanks :)
Upvotes: 1
Views: 1712
Reputation: 642
ConditionVariable
& ExecutorService
is more suitable for this scene.
see here for android blog
Upvotes: 0
Reputation: 1302
Check out AsyncTask
class from android.os.AsyncTask
package.
EDIT: Sorry for the quick answer. I have improved it according to OP's needs.
private class MyTask extends AsyncTask<Void, Void, Car> {
@Override
protected Car doInBackground() {
// Create your Car here
return car;
}
@Override
protected void onPostExecute(Car car) {
// This will be executed on UI thread after completion
}
}
And trigger it like this
MyTask task = new MyTask();
task.execute();
If you need to pass parameters to your AsyncTask
, you can add your parameter object to class definition, and of course pass your parameter object while executing your task.
private class MyTaskWithParams extends AsyncTask<String, Void, Car> {
@Override
protected Car doInBackground(String parameter) {
// Create your Car using the String you passed
return car;
}
@Override
protected void onPostExecute(Car car) {
// This will be executed on UI thread after completion
}
}
With the parameter added to definition, you should instantiate with
MyTask2 task2 = new MyTask2();
task2.execute("SomethingSomething");
Upvotes: 3