Reputation: 3
This is my broadcast receiver. I have added all the details that were required but still it is not working
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.widget.Toast;
public class myBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager connectivityManager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "Connected" + isConnected);
else
Log.i("NET", "Not Connected" + isConnected);
}
}
and the manifest file as, I have added all the details the were required but still it is not working
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.mybroadcastreceiver">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<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"
tools:ignore="GoogleAppIndexingWarning">
<receiver android:name=".myBroadCastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
I have worked everything out but this is not working, any idea what can be missing, I have not made a change in MainActivity.java
, could that be the reason?
Upvotes: 0
Views: 1042
Reputation: 20119
Apps targeting Android 7.0 and higher must register the CONNECTIVITY_ACTION broadcast using Context.registerReceiver(BroadcastReceiver, IntentFilter)
. (source)
You can't register it in your manifest, because then your app would wake up every time the user's connectivity changes, which is awful for performance and battery life.
Upvotes: 3