我有Broadcast Receiver
从服务获取字符串值,然后我启动另一个服务。
代码是:
private final BroadcastReceiver entryIdReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
entry_id = intent.getStringExtra(ENTRY_ID);
startVideoService();
}
};
private void startVideoService() {
Intent intentService = new Intent(this, VideoService.class);
intentService.putExtra(ENTRY_ID, entry_id);
startService(intentService);
}
它在MainActivity
。
问题是我尝试多次运行此代码,并且Service类中的entry_id始终为null! 然后我更改了上面的代码,将startVideoService()中的entry_id作为参数传递,并且它有效。
有效的代码:
private final BroadcastReceiver entryIdReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
entry_id = intent.getStringExtra(ENTRY_ID);
startVideoService(entry_id);
}
};
private void startVideoService(String entry_id) {
Intent intentService = new Intent(this, VideoService.class);
intentService.putExtra(ENTRY_ID, entry_id);
startService(intentService);
}
我无法理解为什么上面的第一个版本没有用。由于entry_id是一个范围超出BroadcastReceiver
范围的变量,不应该有效吗?