问题
I am stuck in a problem. I have a broadcast receiver that calls the method of class takes in context and main activity reference in constructor. I dont know how to access main activity in broadcast receiver.Here is my code:
public void onReceive(@NonNull Context context, @NonNull Intent intent) {
if (context == null) {
throw new IllegalArgumentException();
}
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null) {
if (info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI) {
Class myclass = new Class(context,mainactivity reference); //dont know how to get main activity here
}
}
}
}
Is there is any way that I can get it without Intent or there is some other method. I am in learning phase any help will be appreciated.
In manifest:
<receiver android:name="myreceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
回答1:
Try this hope it works:
in Main Activity:
public class MainActivity extends Activity {
public static MainActivity getInstance() {
return new MainActivity();
}
}
And in your receiver:
MainActivity reference=MainActivity.getInstance();
回答2:
I dont know how to access main activity in broadcast receiver
You don't. If this is a manifest-registered receiver, you may not have an instance of this activity, anyway.
Either:
Register the receiver from inside the
Activity, viaregisterReceiver(), in which case your nestedBroadcastReceiverclass can reference the outerActivityinstance, orUse an event bus (greenrobot's EventBus,
LocalBroadcastManager, etc.) to publish your event, and have your activity subscribe on that bus (if the activity happens to be around)
来源:https://stackoverflow.com/questions/43982396/accessing-main-activity-in-broadcast-reciever-without-using-intent