Search code examples
androidandroid-activitybroadcastreceivermain-activity

Accessing main activity in Broadcast Reciever without using intent


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> 

Solution

  • 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();