我是一名 Android 开发人员,在处理库项目 时遇到问题。 我想等到 RegistrationIntentService 返回 token 值。
请看我的第一个线程方法:
我希望我的主线程在继续之前等待另一个线程(包含注册 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;
}
预先感谢您的回答。
最佳答案
如果你想在返回某些东西之前等待线程完成,你可以使用执行器服务来启动线程并等待线程终止。请找到如下示例代码,
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";
}
关于java - 等待来自 RegistrationIntentService 的 token 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42534928/