以下是使用BroadcastReceiver监听网络连接状态改变的完整攻略:
- 在AndroidManifest.xml文件中添加权限和声明BroadcastReceiver:
<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />
<receiver
android:name=\".NetworkChangeReceiver\"
android:enabled=\"true\"
android:exported=\"true\">
<intent-filter>
<action android:name=\"android.net.conn.CONNECTIVITY_CHANGE\" />
</intent-filter>
</receiver>
- 创建NetworkChangeReceiver类并继承BroadcastReceiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// 网络已连接
Toast.makeText(context, \"网络已连接\", Toast.LENGTH_SHORT).show();
} else {
// 网络断开连接
Toast.makeText(context, \"网络已断开\", Toast.LENGTH_SHORT).show();
}
}
}
}
示例说明1:注册BroadcastReceiver
NetworkChangeReceiver receiver = new NetworkChangeReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(receiver, filter);
示例说明2:取消注册BroadcastReceiver
unregisterReceiver(receiver);
以上是使用BroadcastReceiver监听网络连接状态改变的完整攻略。通过注册BroadcastReceiver并在onReceive()方法中处理网络连接状态的改变,您可以实时获取网络连接状态的变化并做出相应的处理。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Android使用BroadcastReceiver监听网络连接状态的改变 - Python技术站