我正在尝试将一个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.
}
}
最佳答案
您的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);
}