我有一个简单的问题。
我在主活动中声明了文本视图,并从XML(findViewById
)创建了它。我想将此值传递给广播接收器的子类。以下是我的Broadcast构造函数:
public Broadcast(TextView text_dBm) {
this.text_dBm = text_dBm;
}
在我的主要活动中,我创建了一个新的广播对象,并在其中传递我的textview值,如下所示:
new Broadcast(text_dBm);
但是我的text_dBm
上仍然出现空指针异常。无论如何(除了静态方法)在活动和广播接收器之间传递值?
哦,是的。我的广播接收器以编程方式(在服务中)注册,并且运行良好。
感谢您的时间!
P.S:我已经在SO中检查了一些线程,但我没有找到答案:
How to pass value from an activity in an broadcast receiver?
主要活动类:
public class MainActivity extends Activity {
TextView text_dBm, text_time, text_rssi;
Intent startServiceFromActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text_dBm = (TextView) findViewById(R.id.textView_dBm);
new Broadcast(text_dBm);
startServiceFromActivity = new Intent(this, WifiService.class);
startService(startServiceFromActivity);
}
}
广播接收器类:
public class Broadcast extends BroadcastReceiver {
WifiInfo wifiInfo;
WifiManager wifiManager_service;
TextView text_dBm;
public Broadcast(WifiManager wifiManager_service) {
this.wifiManager_service = wifiManager_service;
}
public Broadcast(TextView text_dBm) {
this.text_dBm = text_dBm;
}
@Override
public void onReceive(Context context, Intent intent) {
Log.d("RECEIVER", "Receiver running"); // LOG
text_dBm.setText("textview"); // nullpointerexception
}
}
答案 0 :(得分:2)
通过意图传递数据
活动 -
Intent i = new Intent(Activity.this, Broadcast.class);
Bundle b = new Bundle();
b.putString("key", "value");
i.putExtras(b);
startActivity(i);
在您的广播接收器类onReceive
方法
@Override
public void onReceive(Context context, Intent intent)
{
String result = intent.getString("key");
// your method
}
答案 1 :(得分:2)
您无法使用Intent传递视图。要做你想做的事,你需要你的广播接收器成为你活动的内在阶层。当活动开始和在活动停止时取消注册时,应注册接收者。否则你会泄漏记忆。这意味着您只能在活动屏幕上实际收到消息。
如果您需要能够在活动之外接收广播,则需要:
来自你的评论:
-
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbmView = (TextView) findViewById(R.id.textView_dBm);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter("com.example.broadcasts.DBM_UPDATE");
registerReceiver(receiver, intentFilter);
}
@Override
protected void onStop() {
unregisterReceiver(receiver);
super.onStop();
}
private TextView dbmView;
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
dbmView.setText(intent.getStringExtra("dbm"));
}
}
}
在服务中:
Intent i = new Intent("com.example.broadcasts.DBM_UPDATE");
i.putExtra("dbm", "it works!");
sendBroadcast(i);