4

在我的一个课程中,我尝试访问一个视图(在我的主布局中)以响应收到的广播:

  protected BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context ctx, Intent intent) {
      String action = intent.getAction();
      if ( action.equals("com.mydomain.myapp.INTERESTING_EVENT_OCCURRED") ) {
        ((Activity) ctx).setContentView(R.layout.main);
        LinearLayout linLayout = (LinearLayout) findViewById(R.id.lin_layout);
        if (linLayout != null) {
          Log.i(TAG_OK, "OK to proceed with accessing views inside layout");
        }
        else
          Log.e(TAG_FAIL, "What's wrong with calling findViewById inside onReceive()?");
      }
    }       
  };  

问题是 findViewById() 总是返回 null,因此我总是收到 TAG_FAIL 错误消息。

活动的onCreate()中的完全相同的 findViewById(R.id.lin_layout)调用返回所需的结果,所以我知道这不是上面引用的代码中的拼写错误或其他错误。

为什么会这样?

BroadcastReceiver中调用findViewById()是否有限制?

还是其他原因?

4

1 回答 1

4

BroadcastReceiver 是它自己的类,不继承自android.app.Activity,是吗?所以按照这个逻辑,你不能指望它包含 Activity 的方法。

将上下文传递给您的 BroadcastReceiver,或者更直接地,传递对您要操作的视图的引用。

// package protected access
LinearLayout linLayout;

onCreate()
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    linLayout = (LinearLayout) findViewById(R.id.lin_layout);
}

protected BroadcastReceiver myReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context ctx, Intent intent)
    {
        String action = intent.getAction();
        if ( action.equals("com.mydomain.myapp.INTERESTING_EVENT_OCCURRED"))
        {
            if (linLayout != null)
            {
                Log.i(TAG_OK, "OK to proceed with accessing views inside layout");
            }
            else
                Log.e(TAG_FAIL, "What's wrong with calling findViewById inside onReceive()?");
            }
        }       
    };  
于 2013-05-06T01:12:30.710 回答