从互联网下载文件并仅在网络可用时注册广播接收器

Download file from internet and register broadcast receiver only with network available

我正在开发一个应用程序,它需要在后台从网络服务器下载一个 json 文件并将其存储在外部存储器中,每次加载 activity 它都会填充通过首先读取文件来获取数据(如果没有文件,它将使用资产文件),但在后台(每次经过一定的时间),它将更新文件。

问题是我设法做到了,而且工作正常,但前几天我将设备置于飞行模式,当你输入 activity 时,下载开始了,但由于以下事实没有互联网连接,通知栏中的下载图标不会消失,这对用户体验来说是一种不良行为。 所以我想问一下如何改变这个,只有在有互联网连接的情况下才下载文件。

这是代码:

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();
    }

非常感谢您:)

 public static boolean isNetworkStatusAvialable (Context context) {
    ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivityManager != null) 
    {
        NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
        if(netInfos != null)
            if(netInfos.isConnected()) 
                if (netInfos.isAvailable())
                    return true;
    }
    return false;

}
 In yourActivity
    if .isNetworkStatusAvialable(getApplicationContext())) {
your stuff
}
else {
  Toast.makeText(getApplicationContext(), "Turn on Internet Connection", Toast.LENGTH_SHORT).show();
}

最后我做了这个方法:

private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

然后:

if (isNetworkAvailable()) {
            inicializarFecha();
            if (comprobarFecha()) {
                downloadFile(getActivity());
            }
        /* Gestionar la actualizacion del fichero de establecimientos */

            String downloadCompleteIntentName = DownloadManager.ACTION_DOWNLOAD_COMPLETE;
            final 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, -1);
                    DownloadManager.Query query = new DownloadManager.Query();
                    query.setFilterById(downloadId);
                    Log.e("QUERY", "broadcast " + String.valueOf(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_ESTABLECIMIENTOS, "Descarga realizada con éxito");
                                File file = context.getExternalFilesDir(null);
                                String mFileNameNew = file.getPath() + "/" + AppConstants.TAG_ESTABLECIMIENTOS + "-1";
                                File establecimientosFileNew = new File(mFileNameNew);
                                // Existe uno nuevo
                                if (establecimientosFileNew.exists()) {
                                    Log.e("entro", "existe uno nuevo");
                                    String establecimientosFileOld = file.getPath() + "/" + TAG_ESTABLECIMIENTOS;
                                    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, "Establecimientos actualizados", Snackbar.LENGTH_SHORT).show();
                                    }
                                }
                                break;

                            case DownloadManager.STATUS_FAILED:
                                int columnReasonIndex = cur.getColumnIndex(DownloadManager.COLUMN_REASON);
                                Log.e(AppConstants.TAG_ESTABLECIMIENTOS, "Descarga fallida: " + cur.getInt(columnReasonIndex));
                                break;
                        }

                    }

                    cur.close();
                    cur = null;
                }
            };
            getActivity().registerReceiver(mDownloadEstablecimientosComplete, downloadCompleteIntentFilter);
        }

现在一切正常,但主要问题是为什么要设置飞行模式

request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI | DownloadManager.Request.NETWORK_MOBILE);

无论如何都会尝试下载文件