将bundle从service传递给receiver返回null

时间:2017-05-13 08:19:18

标签: android service broadcastreceiver localbroadcastmanager

将捆绑从服务传递到接收方返回null

  

我想将数据从服务传递到接收器以立即更改ui数据

     

我已将数据包作为hashmap键传递,并在活动类中获得相同但始终为null   我只是在清单

中的代码中注册registerReceiver

主要活动

class Counter {
    async run() {
        await this.one();
        await this.two();
        await this.three();
    }
    async one() {
        console.log('one');
    }
    async two() {
        console.log('two');
    }
    async three() {
        console.log('three');
    }
}
let counter = new Counter();
counter.run();

服务(火力地堡)

BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (intent != null) {

                    Bundle extras = intent.getBundleExtra("hashmap");
                    Toast.makeText(context, extras + "  " + intent.getBundleExtra("hashmap"), Toast.LENGTH_SHORT).show();


                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };


    @Override

    protected void onResume() {
        super.onResume();
        try {
            LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(FIRMessagingService.REQUEST_ACCEPT));
        } catch (Exception e) {
            e.printStackTrace();

        }
       /* try {
            registerReceiver(receiver, new IntentFilter(FCMActivity.NEW_NOTIFICATION));
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);


        } catch (Exception e) {

        }
        /*try {
            unregisterReceiver(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }

4 个答案:

答案 0 :(得分:1)

data_fin.removeIf(a -> a[2] != 0);

答案 1 :(得分:0)

这是因为您的HashMap数据为空。您正在创建一个HasMap的新对象,并尝试从中获取实际为空的值。

HashMap<String, String> data = new HashMap<>();

答案 2 :(得分:0)

尝试使用onMessageReceived中添加的一些键(与R.strings一起保存)而不是intent.getBundleExtras(&#34; hashmap&#34;)

的extra.getString(key)

答案 3 :(得分:0)

  

因为你刚刚初始化它。但是从不将数据传递给地图对象。所以map始终为null。尝试以下代码

 Map<String, String> data = remoteMessage.getData();


        Bundle msg = new Bundle();
        for (String key : data.keySet()) {
            Log.e(key, data.get(key));
            msg.putString(key, data.get(key));
        }