KimJoyJoy KimJoyJoy - 3 years ago 187
Android Question

BroadcastReceiver doesn't work?

My Manifest.xml

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:name="android.support.multidex.MultiDexApplication"
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=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
<receiver android:name=".MyBroadCastRecieverInternet">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
</application>


Its my Service code block.

public class MyBroadCastRecieverInternet extends BroadcastReceiver {

public void onReceive(final Context context, Intent intent) {
Log.d("MyLog","Internet Reciever is on");
}

}


Is there any mistake? I didn't find anything. It doesn't work and I don't know why.

Answer Source

From docs:

Apps targeting Android 7.0 (API level 24) and higher do not receive CONNECTIVITY_ACTION broadcasts if they declare their broadcast receiver in the manifest. Apps will still receive CONNECTIVITY_ACTION broadcasts if they register their BroadcastReceiver with Context.registerReceiver() and that context is still valid.

CONNECTIVITY_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";

You can downgrade your targetSdk to 23 or use dynamic broadcast receiver like this:

public class ConnectivityReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        boolean isConnected = ConnectionManager.isConnectedToInternet(context);

        if (!isConnected) {
            Toast.makeText(context, "Connected", Toast.LENGTH_SHORT).show();
        }
    }
}

MainActivity:

public class MainActivity extends AppCompatActivity {

    private Context mContext = this;

    private ConnectivityReceiver mConnectivityReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mConnectivityReceiver = new ConnectivityReceiver();
    }

    @Override
    protected void onResume() {
        super.onResume();

        registerReceiver(mConnectivityReceiver, new IntentFilter(
                ConnectivityManager.CONNECTIVITY_ACTION
        ));
    }

    @Override
    protected void onPause() {
        unregisterReceiver(mConnectivityReceiver);

        super.onPause();
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download