未过时接口注册网络监听
整理前辈经验,自己在此做个笔记。 实现实时监听网络的变化。
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private String TAG = "JPush";
private ConnectivityManager connectivityManager;
private NetworkCallbackImpl networkCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerNetworkChange();
}
/**
* 注册网络变化回调
*/
private void registerNetworkChange() {
Object systemService = getSystemService(Context.CONNECTIVITY_SERVICE);
if (systemService instanceof ConnectivityManager) {
connectivityManager = (ConnectivityManager) systemService;
}
if (connectivityManager != null) {
networkCallback = new NetworkCallbackImpl();
NetworkRequest.Builder builder = new NetworkRequest.Builder();
NetworkRequest request = builder.build();
connectivityManager.registerNetworkCallback(request, networkCallback);
} else {
Log.i(TAG, "registerNetworkChange: connectivityManager is null");
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (connectivityManager != null && networkCallback != null) {
connectivityManager.unregisterNetworkCallback(networkCallback);
}
}
// 网络变化回调方式
private class NetworkCallbackImpl extends ConnectivityManager.NetworkCallback {
private String TAG = "JPush";
@Override
public void onAvailable(@NonNull Network network) {
super.onAvailable(network);
// 有网回调这里,如果手机没有联网,这里不回调
Log.i(TAG, "onAvailable: 网络已连接");
}
@Override
public void onLost(@NonNull Network network) {
super.onLost(network);
// 切换网络后,也会回调这里。如果后面再次获得网络,会回调 onCapabilitiesChanged()
Log.i(TAG, "onLost: 网络已断开");
}
@Override
public void onCapabilitiesChanged(@NonNull Network network, @NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)) {
// 再次获得网络,回调这里,所以这里可以处理继续播放视频等
if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
Log.i(TAG, "onCapabilitiesChanged: 当前网络类型为 WiFi");
} else if (networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
Log.i(TAG, "onCapabilitiesChanged: 当前网络为蜂窝网络,即手机流量");
} else {
Log.i(TAG, "onCapabilitiesChanged: 其他网络");
}
}
}
}
}
|