A? findViewById () cannot be called inside onReceive ()?

In one of my classes, I am trying to access a view (in my main layout) in response to the resulting broadcast:

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 wrong with calling findViewById inside onReceive()?"); } } }; 

The problem is that findViewById () always returns null, and as a result, I always get the TAG_FAIL error message.

the same exact findViewById(R.id.lin_layout) call inside the onCreate () action returns the desired result, so I know it's not a typo or some other error in the above code.

Why is this happening?

Is there a restriction on calling findViewById () inside BroadcastReceiver ?

or for any other reason?

+4
source share
1 answer

BroadcastReceiver is its own class and is not inherited from android.app.Activity, right? Therefore, by this logic, you cannot expect it to include Activity methods.

Pass the context to your BroadcastReceiver or more directly, pass the link to the view you want to manipulate.

 // 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 wrong with calling findViewById inside onReceive()?"); } } }; 
+4
source

Source: https://habr.com/ru/post/1479286/


All Articles