java - 等待来自 RegistrationIntentService 的 token 值

标签 java android multithreading

我是一名 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/

相关文章:

java - 在代码上重命名 Android 文件夹

java - 单击列表项时 ViewPager 变为空白

android - Android OpenCV MatToBitmap导致黑色图像

Linux,取消阻塞read()

JavaFX TreeView 的多种对象类型? (和更多)

java - 由体素制成的平面 3D 三角形

Android,Handler 是运行在主线程还是其他线程?

c# - ASP.NET Core线程中默认的IServiceProvider安全吗?

Java Runtime.maxMemory 不正确?

php - 我如何通过我的应用程序检查谁在线?