将整数传递给广播接收器

时间:2017-07-19 10:24:18

标签: android android-broadcast

我有一个由Mqtt客户端从服务器订阅的服务。当我收到消息时,我会广播消息和主题。在我的片段中,我声明了一个像这样的广播接收器:

    private final BroadcastReceiver mChatReceiver = new BroadcastReceiver() {
    int areaCode;

    private BroadcastReceiver init(int areaCode) {
        Log.i("====>", "init: BroadcastReceiver ");
        this.areaCode = areaCode;
        return this;
    }


    @Override
    public void onReceive(Context context, Intent intent) {

        Log.i("====>", "onReceive: BroadcastReceiver ");
        //do sth

    }
}.init(areaCode);

但是init(areaCode)不起作用,原来的areaCode是例如2,但我在private BroadcastReceiver init(int areaCode)中没有获得2。我得到了0。

如何将private final BroadcastReceiver mChatReceiver类中的整数传递给此类?

1 个答案:

答案 0 :(得分:1)

假设您正在注册这样的自定义IntentFilter

IntentFilter filter = new IntentFilter("com.packageName.ACTION_SEND_INTEGER");

像这样注册接收器:

your_context.registerReceiver(mChatReceiver,filter);

像这样触发你的广播接收器并发送一个整数:

Intent intent = new Intent("com.packageName.ACTION_SEND_INTEGER");
        intent.putExtra("your_value",123);
        sendBroadcast(intent);