我正在尝试创建一个互联网连接侦听器。但不起作用。我没有犯任何错误。我认为NetworkStateChangeReceiver根本不起作用。因为 Log.e 不会出现在日志猫中。我是Android的新手,这对我来说很复杂。
安卓清单
<receiver
android:name=".NetworkStateChangeReceiver">
<intent-filter >
<action android:name="com.gdm.retailalfageek.NetworkAvailable" />
</intent-filter>
</receiver>
NetworkStateChangeReceiver.java
public class NetworkStateChangeReceiver extends BroadcastReceiver {
public static final String NETWORK_AVAILABLE_ACTION = "com.gdm.retailalfageek.NetworkAvailable";
public static final String IS_NETWORK_AVAILABLE = "isNetworkAvailable";
@Override
public void onReceive(Context context, Intent intent) {
Intent networkStateIntent = new Intent(NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(IS_NETWORK_AVAILABLE, getConnectionType(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
Log.e("Network Available ", "On receive called");
}
@IntRange(from = 0, to = 2)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
Log.e("Network Available ", "On receive called");
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Log.e("Network Available ", "On receive called");
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
Log.e("Network Available ", "On receive called");
result = 1;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
Log.e("Network Available ", "On receive called");
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
Log.e("Network Available ", "On receive called");
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.e("Network Available ", "On receive called");
result = 1;
}
}
}
}
return result;
}}
应用程序类
@Override
public void onCreate() {
super.onCreate();
IntentFilter filter = new IntentFilter();
filter.addAction("isNetworkAvailable");
registerReceiver(new NetworkStateChangeReceiver(), filter);
}
希望下面给出的代码对您有所帮助。
-
在 Manifest.file 中注册广播接收器
<receiver android:name=".MyBroadcastReceiver" > <intent-filter> <action android:name="android.net.conn.CONNECTIVITY_CHANGE" /> </intent-filter> </receiver>
-
在清单中设置互联网权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET"/>
-
实现接收类。
public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // This will execute upon receiving event } }