BroadcastReceiver类中的变量不能在

时间:2016-09-05 17:23:40

标签: java android

我有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范围的变量,不应该有效吗?

0 个答案:

没有答案