android - 如何将 IntentService 的结果返回到 Activity?

标签 android android-intent

我正在使用 IntentService 通过 JSON 处理与服务器的网络通信。 JSON/服务器部分工作正常,但我无法将结果返回到需要的地方。以下代码显示了我如何从 onClick() 内部启动 Intent 服务,然后让服务更新全局变量以将结果传递回主 Activity 。

public class GXActivity extends Activity {

    private static final String TAG = "GXActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // === called when the activity is first created

        Log.i(TAG, "GXActivity Created");

        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);

        View.OnClickListener handler = new View.OnClickListener() {
            public void onClick(View v) {

                // === set up an application context to hold a global variable
                // === called user, to contain results from the intent service
                GXApp appState = ((GXApp) getApplicationContext());
                User user = new User(-1); // initialize user id to -1
                appState.setUser(user);

                // === next start an intent service to get JSON from the server;
                // === this service updates the user global variable with
                // === results from the JSON transaction
                Intent intent = new Intent(this, GXIntentService.class);
                startService(intent);

                // === check app context for results from intent service
                appState = ((GXApp) getApplicationContext());
                if (appState.getUser().getId() != -1)...

            }
        }
    }
}

我遇到的问题是解析 JSON 的 Intent 服务直到 onCreate() 完成后才会被调用,因此我正在寻找结果的代码在查看未初始化的结果时卡住了。

我应该做些什么不同的事情,以便在我检查结果之前调用 Intent 服务?如果我将点击监听器从 onCreate() 函数中拉出来,它会起作用吗?是否有另一个/更好的方式来构建此代码?非常感谢。

最佳答案

您应该考虑创建自己的 ResultReceiver Activity 中的子类。 ResultReceiver实现 Parcelable所以可以从您的 Activity 传递给您的Service作为 Intent 的额外内容.

你需要这样做:

  1. 实现 ResultReceiver 的子类在您的 Activity 类(class)中。实现的关键方法是onReceiveResult() .此方法为您提供了 Bundle可用于传递您在 Service 中检索的任何信息的结果数据.只需解压缩您需要的数据并使用它来更新您的 Activity 。

  2. 在您的 Activity 中,创建自定义 ResultReceiver 的新实例并将其添加到 Intent用于启动服务。

  3. 在您的ServiceonStartCommand()方法,检索 ResultReceiver通过Intent并将其存储在本地成员变量中。

  4. 一旦你的Service完成它的工作,让它调用send()在 ResultReceiver 上传递您想要发送回 Activity 的任何数据 Bundle .

这是一种非常有效的模式,意味着您不会将数据存储在讨厌的静态变量中。

关于android - 如何将 IntentService 的结果返回到 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334901/

相关文章:

Android Back/Up 按钮并保留之前的 Intent

android - 如何在我的项目中使用 Android Wheel?

android - 捏放大android相机

android - 如何在 linux web 服务器上制作一个 android 应用程序

java - onActivityResult 永远不会被调用

android - onNewIntent 没有被调用

java - fragment 设计

java - Picasso 图片加载回调

android - 用浏览器打开网址

java - startActivity() 强制关闭我的应用程序