我试图从返回的结果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