我正在尝试将一个int值从我的Service传递给CallReceiver类,不幸的是CallReceiver.value总是等于0,即使在设置了另一个值之后也是如此。当我试图将它作为参数传递给构造函数时,情况完全相同,因此使用从service调用的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.
}
}
答案 0 :(得分:13)
您的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);
}