我正在尝试将结果从 an 返回IntentSerivce
到mainactivity
使用意图,但我无法让它工作。接收来自活动的IntentService
意图没有问题,做它的事情并获得一个JSONstring
. 现在剩下的唯一问题是将此字符串发送回活动。
这是mainactivity中的方法:
public String RTConn(String query){
System.out.println("Querying Rotten Tomatoes.");
Intent rtIntent = new Intent(MainActivity.this, RTConnection.class);
rtIntent.putExtra("query", query);
bindService(rtIntent, RTConnection, Context.BIND_AUTO_CREATE);
startService(rtIntent);
String json = getIntent().getStringExtra("json");
return json;
这是 IntentService:
public void onStart(Intent intent, int startId){
System.out.println("intent Received");
String jsonString = rottenTomatoesSearch(intent.getStringExtra("query"));
Intent RTRetur = new Intent(RTConnection.this, MainActivity.class);
RTRetur.putExtra("json", jsonString);
startActivity(RTRetur);
}
显然 startActivity 不工作,但还有什么用呢?(我宁愿不使用广播接收器)。问候彼得 L。
更新
这是 MainActivity 的外观:
public static final String RECEIVE_JSON = "student.kau.RECEIVE_JSON";
private BroadcastReceiver RTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("broadcast Received: "+intent.getAction());
if(intent.getAction().equals(RECEIVE_JSON)){
System.out.println("JSON Received.");
String serviceJsonString = intent.getStringExtra("json");
}
}
};
此代码是 onCreate:
LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(this);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(RECEIVE_JSON);
bManager.registerReceiver(RTReceiver, intentFilter);
这是方法:
public void onStart(Intent intent, int startId){
System.out.println("intent Received");
String query = intent.getStringExtra("query");
String jsonString = rottenTomatoesSearch(query);
System.out.println("Fetching done");
Intent RTRetur = new Intent(MainActivity.RECEIVE_JSON);
System.out.println("action: "+RTRetur.getAction());
RTRetur.putExtra("json", jsonString);
sendBroadcast(RTRetur);
}
logcat 中的最后一个跟踪是System.out.println("action: "+RTRetur.getAction()");
-action:
student.kau.RECEIVE_JSON