我想将IntentService发送到嵌入的主Activity。我正在使用广播接收器来广播我从IntentService获得的消息:
public static class ResponseReceiver extends BroadcastReceiver {
public static final String ACTION_RESP = "com.mypackage.intent.action.MESSAGE_PROCESSED";
@Override
public void onReceive(Context context, Intent intent) {
String text;
text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
regid = text;
}
}
我已经在主Activity的Oncreate方法中注册了接收器。在这种情况下如何发送“文本”?奇怪的是,在这种情况下,regid为null,而“text”具有我想要的字符串数据。
答案 0 :(得分:1)
您可以使用意向服务的结果接收者将结果导入活动或片段,请按照以下链接
http://sohailaziz05.blogspot.in/2012/05/intentservice-providing-data-back-to.html
答案 1 :(得分:0)
在您的服务中,您可以
Intent intent = new Intent();
intent.setAction(yourActionToMatchBroadcastReceiverIntentFilter);
intent.putExtra(RegistrationIntentService.PARAM_OUT, yourText);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
在活动中注册BroadcastReceiver
中的onResume()
并在onPause()
中取消注册。只要您的活动处于活动状态,接收方就会收到您IntentService
的意图。
修改强>
public static class ResponseReceiver extends BroadcastReceiver {
MapActivity activity;
public ResponseReceiver(MapActivity activity) {
this.activity = activity;
}
@Override
public void onReceive(Context context, Intent intent) {
activity.regid = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
// do whatever you need here
}
}
答案 2 :(得分:0)
注册时,这对我有用
IntentFilter filter = new IntentFilter(ResponseReceiver.ACTION_RESP);
filter.addCategory(Intent.CATEGORY_DEFAULT);
receiver = new ResponseReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, filter);
而不是
registerReceiver(receiver, filter);
@Override
public void onReceive(Context context, Intent intent) {
final String text = intent.getStringExtra(RegistrationIntentService.PARAM_OUT);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
//access the string text and send it to backend
}
});
}
我希望这会对某人有所帮助。像评论中建议的那样发送字符串对我来说不起作用。我在指定ma.regid = text;
的特定行获得了nullpointerexception