实现方法:
- 创建一个BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 这个监听网络连接的设置,连上的时候,改变状态
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Toast.makeText(context, "network is available", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "network is unavailable", Toast.LENGTH_SHORT).show();
}
}
}
- 在需要的地方注册接收器,并设置好网络连接变化的动作:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
- 在AndroidManifest.xml中声明接收器的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<receiver android:name=".NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
以上就是监听网络变化的完整操作流程。
注:从Android N开始,系统更改了广播的使用政策,对静态注册的广播做了限制,大部分的隐式广播(不包括粘性广播和持久性广播)被禁止,否则会报错。因此,建议将NetworkChangeReceiver使用动态注册的方式在Activity或Service中进行注册。
在Android系统中,我们可以通过BroadcastReceiver来监听网络变化。以下是一段简单的示例代码:
- 首先,我们需要创建一个类继承BroadcastReceiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
// 网络可用
Toast.makeText(context, "网络可用", Toast.LENGTH_SHORT).show();
} else {
// 网络不可用
Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show();
}
}
}
- 在AndroidManifest.xml中注册广播:
<receiver
android:name=".NetworkChangeReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
- 需要注意,从Android 7.0开始,系统对隐式广播做了限制,我们需要使用动态注册的方式来接收网络变化的广播。以下是一个简单的示例:
NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);
}
以上代码即可监听网络变化事件,并在网络变化时给出提示。
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/160390.html