7

我正在尝试将一个 int 值从我的 Service 传递给 CallReceiver 类,不幸的是 CallReceiver.value 始终等于 0,即使在设置了另一个值之后也是如此。当我试图将它作为参数传递给构造函数时,情况完全相同,因此使用从服务调用的 setter 方法。真的没有办法传递任何数据吗?

服务:

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;  

接收者:

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.


        }

     }
4

1 回答 1

18

您的CallReceiver mCallReceiver=new CallReceiver();实例不用于接收意图。相反,Android 每次都会创建新实例。0 是未初始化整数变量的默认值。

为确保发生这种情况,请为您的value字段分配一些默认值:

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

并且您的值将始终等于 5。

至于将数据传递给BroadcastReceiver,请将其作为额外内容添加到Intent您正在广播的内容中:

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

然后,在你的CallReceiver

@Override
public void onReceive(Context context, Intent intent) {
    int value=intent.getIntExtra("VALUE", 0);
}
于 2013-01-17T15:58:32.800 回答