在 AndroidManifest.xml 文件中,添加网络状态更改的权限:
然后,在代码中使用一个 BroadcastReceiver 监听网络状态的更改:
public class NetworkStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo networkInfo = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo != null && networkInfo.getState() == NetworkInfo.State.CONNECTED) {
// Download resume code goes here
}
}
}
}
在 onResume() 方法中,注册 BroadcastReceiver:
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(new NetworkStateReceiver(), intentFilter);
}
当网络连接恢复时,在 BroadcastReceiver 的 onReceive() 方法中添加下载恢复代码。