文件下载

本文介绍了一个名为SyncThread的类实现同步下载任务的过程。该类通过继承Runnable接口并在run方法中执行下载操作,利用了单例模式进行实例化。同时,文章详细展示了如何更新下载进度并通过通知的方式反馈给用户。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class SyncThread implements Runnable {
    private static final String TAG = "SyncThread";
    private Context                    mContext;
    private String                     mUrl;
    private String                     mFilename;
    private NotificationManager        mNotifyManager;
    private NotificationCompat.Builder mBuilder;

    private SyncThread(Context ctx, String Url, String filename) {
        this.mContext = ctx;
        mUrl = Url;
        mFilename = filename;
        mNotifyManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(mContext);
    }


    public static SyncThread getInstace(Context ctx, String url, String filename) {
        return new SyncThread(ctx, url, filename);
    }


    @Override
    public void run() {
        //下载文件
        downLoad(mUrl, mFilename);
    }

    private void updateProgress(int progress) {
        mBuilder.setContentText("下载进度" + progress + "%").setProgress(100, progress, false);
        PendingIntent pendingintent = PendingIntent.getActivity(mContext, 0, new Intent(), PendingIntent.FLAG_CANCEL_CURRENT);
        mBuilder.setContentIntent(pendingintent);
        mNotifyManager.notify(0, mBuilder.build());
    }

    private synchronized void downLoad(String murl, String filename) {
        InputStream in = null;
        FileOutputStream out = null;
        int oldProgress = 0;
        try {
            URL url = new URL(murl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.setConnectTimeout(10 * 1000);
            urlConnection.setReadTimeout(10 * 1000);
            urlConnection.setRequestProperty("Connection", "Keep-Alive");
            urlConnection.setRequestProperty("Accept-Language", "zh-CN");
            urlConnection.setRequestProperty("Charset", "UTF-8");
            //urlConnection.setRequestProperty("Accept-Encoding", "gzip, deflate");
            urlConnection.setUseCaches(false);
            urlConnection.connect();
            long bytetotal = urlConnection.getContentLength();
            long bytesum = 0;
            int byteread = 0;
            in = urlConnection.getInputStream();
            File apkFile = new File(ADConstants.getIntance().getDownloadFileDir(mContext), filename);
            out = new FileOutputStream(apkFile);
            byte[] buffer = new byte[1024];
            while ((byteread = in.read(buffer)) != -1) {
                bytesum += byteread;
                out.write(buffer, 0, byteread);
                int progress = (int) (bytesum * 100L / bytetotal);
                if (progress != oldProgress) {
                    updateProgress(progress);
                }
                oldProgress = progress;
            }
            mBuilder.setContentText("下载完毕").setProgress(0, 0, false);
            Log.d(TAG, "下载完毕。。。");
            mBuilder.setContentText("文件检验成功");
            Notification noti = mBuilder.build();
            noti.flags = Notification.FLAG_AUTO_CANCEL;
            mNotifyManager.notify(0, noti);
            mNotifyManager.cancel(0);
        } catch (Exception e) {
            mBuilder.setContentText("下载失败:" + e.getMessage());
            Log.d(TAG, "下载失败。。。:" + e.getMessage());
            Notification noti = mBuilder.build();
            noti.flags = Notification.FLAG_AUTO_CANCEL;
            mNotifyManager.notify(0, noti);
        } finally {
            StreamUtils.closeStream(out);
            StreamUtils.closeStream(in);
        }
    }
}

public class StreamUtils {
    // 关流
    public static void closeStream(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

//使用
SyncThread instace;
    ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
    instace = SyncThread.getInstace(this, Constant.Sound_URL, fileName);
    singleThreadExecutor.execute(instace);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值