Accessing main activity in Broadcast Reciever without using intent

筅森魡賤 提交于 2019-12-12 05:13:20

问题


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, via registerReceiver(), in which case your nested BroadcastReceiver class can reference the outer Activity instance, or

  • Use 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!