咦? findViewById()无法在onReceive()里面调用?

时间:2013-05-06 00:52:01

标签: android broadcastreceiver findviewbyid

在我的一个班级中,我尝试访问一个View(在我的主布局中)以响应收到的广播:

  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)调用会返回所需的结果,因此我知道是一个错字或其他错误上面引用的代码。

为什么会这样?

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

或其他一些原因?

1 个答案:

答案 0 :(得分: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()?");
            }
        }       
    };