0

I'm using a BroadcastReceiver to check network state which extends a class rather than initializing BroadcastReceiver. So, is it possible to unregister it anywhere?

If yes then how, if not then what would be the alternate solution of doing that. I see a solution here but it isn't the actual answer of the question.

Here's my class where I am using BroadcastReceiver.

 public class CheckNetworkState extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        /*check WIFI state*/
        final android.net.NetworkInfo wifi = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        /*check network state*/
        final android.net.NetworkInfo mobile = connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

        if (wifi.isAvailable() || mobile.isAvailable()) {
            //Toast.makeText(context, "connection established", Toast.LENGTH_SHORT).show();
        } else {
            /*shows dialogue*/
            Intent alertDialogueIntent = new Intent(context, DialogueUtils.class);
            alertDialogueIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(alertDialogueIntent);
        }
    }
}

And here's my Manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.hardware.camera" />
<uses-permission android:name="android.hardware.camera.autofocus" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".Utils.DialogueUtils" />
    <receiver
        android:name=".Utils.CheckNetworkState"
        android:enabled="true">
        <intent-filter>
            <action
                android:name="android.net.conn.CONNECTIVITY_CHANGE"
                tools:ignore="BatteryLife" />
        </intent-filter>
    </receiver>

    <activity android:name=".UserAuth.ChangePassword"></activity>
    <activity android:name=".QRScanner.CustomScanner" />
    <activity android:name=".WaterMetersList.WaterMeters" />
    <activity android:name=".UserAuth.Login" />
    <activity
        android:name=".ControlCharts.Charts"
        android:label="@string/title_activity_bottom_navigation" />
    <activity android:name=".Splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
Irfan Akram
  • 718
  • 1
  • 11
  • 20
  • Do you know about `otto` or `EventBus` ? You can archive this by using that – M D Mar 19 '19 at 06:40
  • @MD - sorry, I've no idea about these. – Irfan Akram Mar 19 '19 at 06:43
  • Check in google more – M D Mar 19 '19 at 06:43
  • There is a dirty workaround of that, you need to create static object on application level in your application class. After that you can access that object from anywhere in your app and you can do operations like unregisterReceiver() by passing that object.But this may results in memory leaks. – Muhammad Saad Rafique Mar 19 '19 at 06:53
  • @M.SaadLakhan - Is there an alternative of doing that but with efficient way? – Irfan Akram Mar 19 '19 at 06:57
  • I dont think so because you need an object to unregister. I did this in a way I talked about and it is not producing any issues, app is running fine. So you can go with that approach. – Muhammad Saad Rafique Mar 19 '19 at 07:01
  • @M.SaadLakhan - Can you post the way to do so as an answer? It would be great help. Thank you! – Irfan Akram Mar 19 '19 at 07:05
  • I don't understand what you want to do. You have declared in the manifest that you are interested in CONNECTIVITY_CHANGE events. If you are targeting API level 24 (Android 7.0) or higher, Android won't trigger your `BroadcastReceiver` on these events. What do you mean you want to **unregister** the receiver? Have you actually programatically **registered it**? – David Wasser Mar 26 '19 at 15:45

1 Answers1

0

In your application class create static receiver as follows:

public class YourApplication extends Application {

    public static BroadcastReceiver receiver;

    public void onCreate() {
        super.onCreate();
        receiver = new CheckNetworkState(); 
    }
}

After that you can register your receiver anywhere as:

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

this.registerReceiver(YourApplication.receiver, filter);

After that you can unregister it as:

getContext().unregisterReceiver(YourApplication.receiver);
Muhammad Saad Rafique
  • 3,158
  • 1
  • 13
  • 21
  • you need context if you are in activity you can replace get context with this keyword so it will be like this.unregisterReceiver(YourApplication.receiver); – Muhammad Saad Rafique Mar 19 '19 at 07:27
  • Now it is showing red line error on `MyApplication.receiver` as **Cannot resolve method 'registerReceiver(android.content.BroadcastReceiver)'** – Irfan Akram Mar 19 '19 at 07:34
  • I have edited the answer at time of registration you need to provide filter. Check updated answer add an intent filter then you will be good to go. – Muhammad Saad Rafique Mar 19 '19 at 09:02
  • just before registering your receiver create an intent filter as IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION); – Muhammad Saad Rafique Mar 19 '19 at 09:03