我是一名Android开发人员,我在处理图书馆计划时遇到了问题。 我想等到RegistrationIntentService返回的令牌值。
请用线程查看我的第一个方法:
我希望我的主线程在继续之前等待另一个线程(包含注册Intent服务),然后返回由我的其他线程设置的值。
public Data a(Activity activity){
Data data = new Data();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(activity,RegistrationIntentService.class);
activity.startService(intent);
}
});
thread.start();
// I want my main thread finish until the onHandleIntent of RegistrationIntentService finish
//continue to return data
return data;
}
提前感谢您的回答。
答案 0 :(得分:1)
如果要在返回某个内容之前等待线程完成,可以使用执行程序服务启动该线程并等待终止该线程。请查看以下示例代码,
public String myMethod() {
Thread t = new Thread() {
@Override
public void run() {
// Do Thread Stuff here
}
};
java.util.concurrent.ExecutorService exec = java.util.concurrent.Executors.newSingleThreadExecutor();
exec.execute(t);
// terminate executor after current thread
exec.shutdown();
try {
// Wait till thread completes
exec.awaitTermination(1, java.util.concurrent.TimeUnit.MINUTES);
} catch (InterruptedException e) {
// Handle Exception
}
return "Success";
}