网络监听部分可以参考如下代码:
public class NetworkChangeReceiver extends BroadcastReceiver {
private boolean connected = false;
private OnNetworkChangeListener listener;
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected() && !connected) {
connected = true;
if (listener != null) {
listener.onNetworkConnected();
}
} else if (info == null && connected){
connected = false;
if (listener != null) {
listener.onNetworkDisconnected();
}
}
}
public void setOnNetworkChangeListener(OnNetworkChangeListener listener){
this.listener = listener;
}
public interface OnNetworkChangeListener {
void onNetworkConnected();
void onNetworkDisconnected();
}
}
以上代码实现了简单的网络监听,当网络状态发生变化时,通过 OnNetworkChangeListener 接口回调通知监听者。修改一下 onReceive 方法里面的代码,即可实现你所需要的功能。同时,需要在 AndroidManifest.xml 文件中注册广播接收器:
<receiver android:name=".NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
注册完成之后,就可以开始监听网络状态了。另外,需要注意的是,由于 android.net.conn.CONNECTIVITY_CHANGE 是系统级别的广播,因此需要在 AndroidManifest.xml 文件中进行静态注册,而不能通过代码动态注册。
可能的原因:
- 权限问题:需要在 AndroidManifest.xml 文件中添加访问网络状态的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
- 监听线程问题:需要启动一个新的线程监听网络状态,不能在主线程中执行网络操作。
下面是一个示例代码,可以在网络连接上时弹出 Toast 消息:
public class MainActivity extends AppCompatActivity {
private boolean isConnected = false;
private Toast toast;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 初始化 Toast
toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
// 监听网络状态变化
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new NetworkChangeReceiver(), intentFilter);
}
private class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
// 网络已连接
isConnected = true;
// 弹出消息
toast.setText("网络已连接");
toast.show();
} else {
// 网络未连接
isConnected = false;
// 弹出消息
toast.setText("网络未连接");
toast.show();
}
}
}
}
}
发布者:luotuoemo,转转请注明出处:https://www.jintuiyun.com/155510.html