Android 从 IntentService 传递消息到 Activity

Android pass message from IntentService to Activity

我想将消息发送到它嵌套的主 Activity 的 IntentService。我正在使用广播接收器来广播我从 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;
        }
    }

我已经在mainActivity的Oncreate方法中注册了receiver。在这种情况下如何发送 "text" ?奇怪的是,在这种情况下 regid 为空,而 "text" 具有我想要的字符串数据。

您可以使用具有意图服务的用户结果接收器将结果放入 activity 或片段中,点击以下链接,

http://sohailaziz05.blogspot.in/2012/05/intentservice-providing-data-back-to.html

为您服务

Intent intent = new Intent();
intent.setAction(yourActionToMatchBroadcastReceiverIntentFilter);
intent.putExtra(RegistrationIntentService.PARAM_OUT, yourText);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);

在 activity 中注册您的 BroadcastReceiveronResume() 中并在 onPause() 中取消注册。每当您的 activity 处于活动状态时,接收器都会收到来自您的 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
    }
}

注册时,这对我有用

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;

的特定行出现空指针异常