3 回答
TA贡献1820条经验 获得超9个赞
首先,创建一个名为 NetworkChangeReceiver 的类,如下所示:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if ( activeNetworkInfo != null && activeNetworkInfo.isConnected()) {
Toast.makeText(context, "Network is back", Toast.LENGTH_SHORT).show();
}
}
}
每次网络发生变化时,此类都会收到通知,并且函数中的代码onReceive会检查我们是否在线。
下一个,
在您的清单中添加<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 并告诉 Android 您想要过滤此类事件。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.test">
<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">
<receiver android:name=".NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</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>
</manifest>
接下来在您的主要活动中注册这些事件
private BroadcastReceiver mNetworkReceiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNetworkReceiver = new NetworkChangeReceiver();
registerReceiver(mNetworkReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
@Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mNetworkReceiver);
}
TA贡献1752条经验 获得超4个赞
用于处理后台的东西
您可以使用WorkManager(部分Android Jetpack
)或Android-Job在后台检查互联网连接,这些是在后台处理作业的最佳库。
工作经理is a new architecture component from Google and tries to solve a very similar problem this library tries to solve: implementing background jobs only once for all Android versions.
Android-作业 is a utility library for Android to run jobs delayed in the background.
用于处理前台的东西
TA贡献1795条经验 获得超7个赞
聆听 Android 的连接变化networkCallBack:
https://developer.android.com/reference/android/net/ConnectivityManager#registerNetworkCallback(android.net.NetworkRequest,%20android.net.ConnectivityManager.NetworkCallback)
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
connectivityManager.registerNetworkCallback(
new NetworkRequest.Builder().build(),
new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
super.onAvailable(network);
// ...
}
@Override
public void onLost(Network network) {
super.onLost(network);
// ...
}
});
添加回答
举报