我正在开发一个应用程序,该应用程序需要在后台从 Web 服务器下载 json 文件并将其存储在外部存储器中,每次加载活动时,它都会通过首先读取文件来填充数据(如果没有文件,它将使用资产文件),但在后台(每次经过一定时间)它会更新文件。
问题是我设法做到了这一点并且工作正常,但是前几天我将设备置于飞行模式,当您进入活动时,下载开始,但由于没有互联网连接,下载图标在通知栏不会消失,这对用户体验来说是一种不好的行为。所以我问如何更改它,并且只有在有互联网连接的情况下才下载文件。
这是代码:
if (comprobarFecha()) {
downloadFile(getActivity());
}
String downloadCompleteIntentName = DownloadManager.ACTION_DOWNLOAD_COMPLETE;
IntentFilter downloadCompleteIntentFilter = new IntentFilter(downloadCompleteIntentName);
BroadcastReceiver mDownloadEstablecimientosComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
DownloadManager dm = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -2);
DownloadManager.Query query = new DownloadManager.Query();
Log.e("QUERY", "broadcast " + String.valueOf(downloadId));
query.setFilterById(downloadId);
Cursor cur = dm.query(query);
if (cur.moveToFirst()) {
int columnIndex = cur.getColumnIndex(DownloadManager.COLUMN_STATUS);
switch (cur.getInt(columnIndex)) {
case DownloadManager.STATUS_SUCCESSFUL:
// Como se ha completado con éxito borramos el archivo antiguo
Log.e(AppConstants.TAG_RECETA, "Descarga realizada con éxito");
File file = context.getExternalFilesDir(null);
String mFileNameNew = file.getPath() + "/" + AppConstants.TAG_RECETAS + "-1";
File establecimientosFileNew = new File(mFileNameNew);
// Existe uno nuevo
if (establecimientosFileNew.exists()) {
Log.e("entro", "existe uno nuevo");
String establecimientosFileOld = file.getPath() + "/" + AppConstants.TAG_RECETAS;
File mFileNameOld = new File(establecimientosFileOld);
if (mFileNameOld.exists()) {
// Borramos el viejo
mFileNameOld.delete();
// Renombramos el nuevo
Log.e("entro", "renombramos el nuevo");
establecimientosFileNew.renameTo(mFileNameOld);
Snackbar.make(mSnackBarView, "Recetas actualizadas", Snackbar.LENGTH_SHORT).show();
}
}
break;
case DownloadManager.STATUS_FAILED:
int columnReasonIndex = cur.getColumnIndex(DownloadManager.COLUMN_REASON);
Log.e(AppConstants.TAG_RECETAS, "Descarga fallida: " + cur.getInt(columnReasonIndex));
break;
}
}
cur.close();
cur = null;
}
};
getActivity().registerReceiver(mDownloadEstablecimientosComplete, downloadCompleteIntentFilter);
public void downloadFile(Context ctx) {
DownloadManager mDownloadManager = (DownloadManager) ctx.getSystemService(Context.DOWNLOAD_SERVICE);
String url_download = url + cod;
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url_download));
// Tipo de archivo
request.setMimeType("application/json");
// Solo descargamos con WIFI
request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);
// Titulo
request.setTitle("Descarga recetas");
// No será visible en el historial de descargas
request.setVisibleInDownloadsUi(false);
//request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Guardamos el archivo
request.setDestinationInExternalFilesDir(ctx, null, TAG_RECETAS);
// Guardamos el id para notificación cuando acabe
long quequeId = mDownloadManager.enqueue(request);
Log.e("QUERY", "download " + String.valueOf(mDownloadManager.enqueue(request)));
}
如果我首先创建一种检测互联网连接的方法,并且仅在我的网络服务按预期工作时才启动这些方法..但我不知道这是否是它应该工作的方式,我知道这个问题可能更多的是关于广播接收器如何工作而不是编程问题
我的意思是我的解决方案是这样的:
if (isNetworkAvailable()) {
inicializarFecha();
if (comprobarFecha()) {
downloadFile(getActivity());
}
String downloadCompleteIntentName = DownloadManager.ACTION_DOWNLOAD_COMPLETE;
IntentFilter downloadCompleteIntentFilter = new IntentFilter(downloadCompleteIntentName);
BroadcastReceiver mDownloadEstablecimientosComplete = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
....
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
提前非常感谢你:)