Reputation: 1555
i have one problem with handling the thread in android ,in my class i have to create one thread which create some UI after that thread finish i will get some value ,here i want to wait my Main Process until the thread complete it process but when i put wait() or notify in Main process thread does not show the UI in my application
this is sample code
protected void onCreate(Bundle savedInstanceState) {
downloadThread = new MyThread(this);
downloadThread.start();
synchronized(this){
try {
this.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String test=Recognition.gettemp();
public class MyThread extends Thread {
private Recognition recognition;
public MyThread(Recognition recognition) {
this.recognition = recognition;
// TODO Auto-generated constructor stub
}
@Override
public void run() {
synchronized(this)
{
handler.post(new MyRunnable());
}
notifyAll();
}
}
}
static public class MyRunnable implements Runnable {
public void run() {
settemp(template);
}
}
}
public static String gettemp() {
return template;
}
public static void settemp(String template) {
Recognition.template = template;
}
}
here i will not use AsynTask because i have some other issue that is reason i choose Thread even now the problem is Thread wait do any give the suggestion for this
Upvotes: 0
Views: 1511
Reputation: 7435
This is not an solution just a advice on how should you structure you activity/app.
You should never block the main thread by calling wait()
its a bad user experience and not advised. It would also case a Android Not Responding (ANR) popup.
You can have you thread updating the UI from the background and let the UI to be responsive. Load the static part of your UI in onCreate()
and then fire up the background thread to lazy load rest of the component.
Upvotes: 0
Reputation: 423
What do you expect to happen if you freeze the main UI thread?
You should be using an ASyncTask to show your gui in the onPreExecute method, do the task in doInBackground then display the result in the onPostExecute method.
As a plus you can update the progress using onProgressUpdate too.
Upvotes: 0
Reputation: 591
Use the logic below :-
new Thread(new Runnable()
{
@Override
public void run()
{
//do the code here such as sending request to server
runOnUiThread(new Runnable()
{
@Override
public void run()
{
//do here the code which interact with UI
}
});
}
}).start();
Upvotes: 0
Reputation: 33534
- Use java.util.CountDownLatch
, here you can let some process complete before kick-off some other code.
- countDown()
and await()
will be of use to you.......
See this example of CountDownLatch:
http://www.javamex.com/tutorials/threads/CountDownLatch.shtml
Upvotes: 1