我正在使用 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
的额外内容.
你需要这样做:
实现
ResultReceiver
的子类在您的 Activity 类(class)中。实现的关键方法是onReceiveResult()
.此方法为您提供了Bundle
可用于传递您在Service
中检索的任何信息的结果数据.只需解压缩您需要的数据并使用它来更新您的 Activity 。在您的 Activity 中,创建自定义
ResultReceiver
的新实例并将其添加到Intent
用于启动服务。在您的
Service
的onStartCommand()
方法,检索ResultReceiver
通过Intent
并将其存储在本地成员变量中。一旦你的
Service
完成它的工作,让它调用send()
在 ResultReceiver 上传递您想要发送回 Activity 的任何数据Bundle
.
这是一种非常有效的模式,意味着您不会将数据存储在讨厌的静态变量中。
关于android - 如何将 IntentService 的结果返回到 Activity?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10334901/