我正在使用IntentService通过JSON与服务器处理网络通信。 JSON / 服务器部分工作正常,但我在将结果返回到需要它们的位置方面遇到了问题。以下代码显示了我如何从onClick()内部启动意图服务,然后使服务更新全局变量以将结果传递回主活动。
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()函数中拉出来,是否有效?还有其他更好的编写代码结构的方法吗?非常感谢。