我有这个IntentService(HttpService
)从webservice中获取原始json数据:
public class HttpService extends IntentService {
public static final String BROADCAST_ACTION = "com.example.HttpService";
public HttpService() {
super("HttpService");
}
@Override
protected void onHandleIntent(Intent intent) {
//code to get a String with jsonData
//Then I send a broadcast
Intent broadcastHttpResponseIntent = new Intent();
broadcastHttpResponseIntent.setAction(BROADCAST_ACTION);
broadcastHttpResponseIntent.putExtra("jsonData", jsonData);
sendBroadcast(broadcastHttpResponseIntent);
}
}
现在来自使用HttpService
的IntentService,我试图接收广播:
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
public RestaurantModel() {
super("RestaurantModel");
}
@Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
BroadcastReceiver httpBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
registerReceiver(httpBroadcastReceiver, new IntentFilter(HttpService.BROADCAST_ACTION));
}
}
所以我收到了这个错误:
RestaurantModel已泄露最初在此注册的IntentReceiver com.example.RestaurantModel $ 1 @ 42374590。你是否错过了对unregisterReceiver()的调用?
所以我尝试取消注册Receiver,但似乎需要一个Context才能取消注册接收者。
如何从IntentService接收到另一个IntentService的值?
答案 0 :(得分:1)
最佳答案是:只有一个IntentService
。
下一个最佳答案是:完全摆脱广播内容,并让第一个IntentService
来电startService()
启动第二个IntentService
。
答案 1 :(得分:1)
同意@CommonsWare,如果你想在IntentService中使用BroadcaseReceiver,请在onCreate方法中注册它并在onDestroy方法中取消注册。
public class RestaurantModel extends IntentService {
public static final String BROADCAST_ACTION = "com.example.RestaurantModel";
private BroadcastReceiver httpBroadcastReceiver;
public RestaurantModel() {
super("RestaurantModel");
}
@Override
public void onCreate() {
super.onCreate();
httpBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.v("RestaurantModel", "onReceive");
String jsonResponse = intent.getStringExtra("jsonData");
}
};
LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(httpBroadcastReceiver);
}
@Override
public void onDestroy() {
super.onDestroy();
LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(httpBroadcastReceiver);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.v("RestaurantModel", "onHandleIntent");
Intent getRestaurantsJsonIntent = new Intent(RestaurantModel.this, HttpService.class);
getRestaurantsJsonIntent.putExtra("urlRestaurants", intent.getStringExtra("urlRestaurants"));
startService(getRestaurantsJsonIntent);
}
}