本文介绍了传递参数给广播接收器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的服务传递一个int值到CallReceiver类,不幸的是CallReceiver.value总是等于0,甚至建立与另一个值之后。当我试图把它作为给构造情况的参数是完全一样的,所以从服务调用setter方法​​。难道真的没有办法通过有没有数据?

服务:

 共享preferences设置= getShared preferences(设置,0);
    int值= settings.getInt(值1,0); //此处正确的值是present,而不是0。
    CallReceiver mCallReceiver =新CallReceiver();
    CallReceiver.value =价值;

接收器:

 公共类CallReceiver扩展广播接收器{公共int值;公共CallReceiver(int值){
    THIS.VALUE =价值;
}公共CallReceiver(){}
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
            Log.v(价值,将String.valueOf(值)); //这里的价值= 0。
        }     }


解决方案

CallReceiver mCallReceiver =新CallReceiver(); 实例未用于接收意图。相反,Android的创建新实例每次。而0是未初始化整型变量的缺省值。

要确保这是什么情况,分配一些默认值,你的字段:

 公共类RReceiver扩展广播接收器{
    公共int值= 5;
    // ...
}

和你的价值始终等于5。

对于将数据传递到广播接收器,将其添加为额外的意图你正在广播:

  //你的服务
意图broadcastedIntent =新意图(这一点,CallReceiver.class);
broadcastedIntent.putExtra(VALUE,100500);
sendBroadcast(broadcastedIntent);

然后,在你的 CallReceiver

  @覆盖
公共无效的onReceive(上下文的背景下,意图意图){
    int值= intent.getIntExtra(VALUE,0);
}

I'm trying to pass an int value from my Service to the CallReceiver class, unfortunately the CallReceiver.value always equals 0, even after set with another value. When I'm trying to pass it as a parameter to the constructor situation is exactly the same, and so with the setter methods called from service. Is there really no way to pass there any data?

Service:

SharedPreferences settings = getSharedPreferences("SETTINGS", 0);
    int value = settings.getInt("value1", 0); // here the correct value is present, not 0.
    CallReceiver mCallReceiver = new CallReceiver();
    CallReceiver.value = value;

Receiver:

public class CallReceiver extends BroadcastReceiver  {

public int value;

public CallReceiver(int value)  {
    this.value = value;
}

public CallReceiver()   {

}


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


            Log.v("value", String.valueOf(value)); // here "value" = 0.


        }

     }
解决方案

Your CallReceiver mCallReceiver=new CallReceiver(); instance is not used for receiving intents. Instead, Android creates new instance each time. And 0 is the default value for uninitialized integer variables.

To make sure this is what happens, assign some default value to your value field:

public class RReceiver extends BroadcastReceiver {
    public int value=5;
    //...
}

and your value will always be equal 5.

As for passing data to BroadcastReceiver, add it as extra to the Intent you are broadcasting:

//in your service
Intent broadcastedIntent=new Intent(this, CallReceiver.class);
broadcastedIntent.putExtra("VALUE", 100500);
sendBroadcast(broadcastedIntent);

And then, in your CallReceiver:

@Override
public void onReceive(Context context, Intent intent) {
    int value=intent.getIntExtra("VALUE", 0);
}

这篇关于传递参数给广播接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-11 13:02