Можно ли отменить регистрацию BroadcastReceiver, который расширяет класс, не создавая из него объект? - PullRequest
0 голосов
/ 19 марта 2019

Я использую BroadcastReceiver для проверки состояния сети, которая расширяет класс, а не инициализирует BroadcastReceiver. Так можно ли его где-нибудь отменить?

Если да, то как, если нет, то каково будет альтернативное решение этого? Я вижу решение здесь , но это не фактический ответ на вопрос.

Вот мой класс, где я использую 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);
        }
    }
}

А вот и мой 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>

1 Ответ

0 голосов
/ 19 марта 2019

В вашем классе приложений создайте статический приемник следующим образом:

public class YourApplication extends Application {

    public static BroadcastReceiver receiver;

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

После этого вы можете зарегистрировать свой приемник в любом месте как:

IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);

this.registerReceiver(YourApplication.receiver, filter);

После этого вы можете отменить его регистрацию как:

getContext().unregisterReceiver(YourApplication.receiver);
...