通过Retrofit 2,Android

时间:2016-04-26 08:20:57

标签: android download retrofit

我目前正在使用Retrofit 2,我想从我的服务器下载一些文件。 我是否可以回拨一些事件以捕获完整下载文件百分比,以便在通知中显示,如此图片enter image description here

我引用该链接,但它是上传,我可以用同样的问题吗? Link

使用改装2库时是否可以显示进度?

2 个答案:

答案 0 :(得分:8)

您可以使用ResponseBody并将其设置为OkHttp客户端,并更新您可以使用界面的UI进度。check this link

答案 1 :(得分:0)

或者,您可以使用here中所述的Intent服务。

我将向您展示如何使用上述内容...唯一的区别是文件写入磁盘的部分。

定义服务:

public class BackgroundNotificationService extends IntentService {

    public BackgroundNotificationService() {
        super("Service");
    }

    private NotificationCompat.Builder notificationBuilder;
    private NotificationManager notificationManager;

    private String mAgentsID;
    private String mReportsID;
    private String mJobID;
    private String mFileName;


    @Override
    protected void onHandleIntent(Intent intent) {

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel notificationChannel = new NotificationChannel("id", "an", NotificationManager.IMPORTANCE_LOW);

            notificationChannel.setDescription("no sound");
            notificationChannel.setSound(null, null);
            notificationChannel.enableLights(false);
            notificationChannel.setLightColor(Color.BLUE);
            notificationChannel.enableVibration(false);
            notificationManager.createNotificationChannel(notificationChannel);
        }


        notificationBuilder = new NotificationCompat.Builder(this, "id")
                .setSmallIcon(android.R.drawable.stat_sys_download)
                .setContentTitle("Download")
                .setContentText("Downloading Image")
                .setDefaults(0)
                .setAutoCancel(true);
        notificationManager.notify(0, notificationBuilder.build());

        mAgentsID = intent.getStringExtra("AgentsID");
        mReportsID = intent.getStringExtra("ReportsID");
        mJobID = intent.getStringExtra("JobID");
        mFileName = intent.getStringExtra("FileName");

        initRetrofit();

    }

    private void initRetrofit(){
        Call<ResponseBody> downloadCall = ApiManager.getJasperReportsService().DownloadAgentReportData(mAgentsID, mReportsID, mJobID, mFileName);

        try {
            writeResponseBodyToDisk(downloadCall.execute().body(), mFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private boolean writeResponseBodyToDisk(ResponseBody body, String FileName) {
        try {
            File SDCardRoot = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
            File DownloadedFile = new File(SDCardRoot + File.separator + FileName);

            InputStream inputStream = null;
            OutputStream outputStream = null;

            try {
                byte[] fileReader = new byte[4096];

                long fileSize = body.contentLength();
                long fileSizeDownloaded = 0;

                long total = 0;
                boolean downloadComplete = false;

                inputStream = body.byteStream();
                outputStream = new FileOutputStream(DownloadedFile);

                while (true) {
                    int read = inputStream.read(fileReader);

                    if (read == -1) {
                        downloadComplete = true;
                        break;
                    }

                    total += read;
                    int progress = (int) ((double) (total * 100) / (double) fileSize);

                    updateNotification(progress);

                    outputStream.write(fileReader, 0, read);

                    fileSizeDownloaded += read;


                    Log.d("DOWNLOAD FILE", "file download: " + fileSizeDownloaded + " of " + fileSize);
                }
                onDownloadComplete(downloadComplete);

                outputStream.flush();

                return true;
            } catch (IOException e) {
                return false;
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            }
        } catch (IOException e) {
            return false;
        }
    }

    private void updateNotification(int currentProgress) {


        notificationBuilder.setProgress(100, currentProgress, false);
        notificationBuilder.setContentText("Downloaded: " + currentProgress + "%");
        notificationManager.notify(0, notificationBuilder.build());
    }


    private void sendProgressUpdate(boolean downloadComplete) {

        Intent intent = new Intent("progress_update");
        intent.putExtra("downloadComplete", downloadComplete);
        LocalBroadcastManager.getInstance(BackgroundNotificationService.this).sendBroadcast(intent);
    }

    private void onDownloadComplete(boolean downloadComplete) {
        sendProgressUpdate(downloadComplete);

        notificationManager.cancel(0);
        notificationBuilder.setProgress(0, 0, false);
        notificationBuilder.setContentText("Download Complete");
        notificationManager.notify(0, notificationBuilder.build());

    }

    @Override
    public void onTaskRemoved(Intent rootIntent) {
        notificationManager.cancel(0);
    }

}

然后使用意图服务:

private void registerReceiver() {

    LocalBroadcastManager bManager = LocalBroadcastManager.getInstance(itemView.getContext());
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("progress_update");
    bManager.registerReceiver(mBroadcastReceiver, intentFilter);

}

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals("progress_update")) {

            boolean downloadComplete = intent.getBooleanExtra("downloadComplete", false);
            //Log.d("API123", download.getProgress() + " current progress");

            if (downloadComplete) {

                Toast.makeText(itemView.getContext(), "File download completed", Toast.LENGTH_SHORT).show();

            }
        }
    }
};

private void startDownload(String jobID, String FileName) {


    Intent intent = new Intent(itemView.getContext(), BackgroundNotificationService.class);
    // TODO customze to suit your own needs.
    intent.putExtra("AgentsID", mAgentsID);
    intent.putExtra("ReportsID", mReportsID);
    intent.putExtra("JobID", jobID);
    intent.putExtra("FileName", FileName);
    itemView.getContext().startService(intent);

}

因此,您在活动开始时使用registerReceiver(),然后如果有一个按钮来启动下载,则您在onClick方法中运行startDownload()。另外,您可以根据需要自定义Intent变量(如果需要)。

相关问题