AsyncTask

下载图片

public void myClick(View view) {
        String imgUrl = "http://img4.duitang.com/uploads/item/201604/29/20160429211449_QjMu4.jpeg";
        // 启动任务
        new ImageTask().execute(imgUrl);
    }

    class ImageTask extends AsyncTask<String, Void, Bitmap> {

        @Override
        protected Bitmap doInBackground(String... params) {
            URL url = null;
            InputStream is = null;
            Bitmap bitmap = null;

            try {
                // 创建URL对象,参数为图片的地址
                url = new URL(params[0]);
                is = url.openStream();
                bitmap = BitmapFactory.decodeStream(is);

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            img.setImageBitmap(bitmap);
        }
    }

这里写图片描述

下载文件

// 文件保存路径
    String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/";
    public void myClick(View view) {
        String downUrl = "http://192.168.1.106/MPC-HC.1.7.10.x86.zip";
        new DownloadTask().execute(downUrl);
    }

    /**
     * @params String  下载路径
     * @params Integer 下载进度
     * @params String 下载结果
     */
    class DownloadTask extends AsyncTask<String, Integer, String> {

        @Override
        protected String doInBackground(String... params) {
            URL url = null;
            InputStream is = null;
            FileOutputStream fos = null;
            String result = "";
            try {
                // 创建URL对象
                url = new URL(params[0]);
                // 打开连接
                URLConnection connection = url.openConnection();
                // 获取下载文件总长度
                int totalLength = connection.getContentLength();
                // 获取输入流
               is= connection.getInputStream();
                int indexOf = params[0].lastIndexOf('/');
                // 截获文件名
                String filename = params[0].substring(indexOf);
                // 获取输出流
               fos = new FileOutputStream(savePath + filename);
                int len = 0;
                int sum = 0;
                byte[] bytes = new byte[1024];
                while (-1!=(len=is.read(bytes))){
                    fos.write(bytes,0,len);
                    sum +=len;
                    // 推送下载进度
                    publishProgress(sum*100/totalLength);
                }
                result = "下载成功";
            } catch (MalformedURLException e) {
                result = "下载失败";
                e.printStackTrace();
            } catch (IOException e) {
                result = "下载失败";
                e.printStackTrace();
            }
            return result;
        }

        /**
         * 在此方法中更新下载进度
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            mTv.setText("当前进度"+values[0]+"%");
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            mTv.setText(s);
        }
    }

这里写图片描述

后台应用升级

/**
 * 应用升级服务
 */
public class DownloadService extends Service {
    private static final String KEY_TAG = "AppDownloadTask";
    public String APP_UPDATE_URL;
    public static String mAppName;
    private static String SAVE_PATH;
    private NotificationManager mManager;
    private static final int NOTIFICATION_ID = (int) (System.currentTimeMillis() / 2);
    private MyTask mTask;
    private int mTotalLength;
    private URLConnection mConnection;
    private URL mUrl;
    private InputStream mInputStream;
    private FileOutputStream mFileOutputStream;

    @Override
    public void onCreate() {
        super.onCreate();
        /**
         * 应用保存地址
         */
        SAVE_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/" + getPackageName() + "-update.apk";
        /**
         * 应用更新路径
         */
        APP_UPDATE_URL = "https://12.shouji.com.cn/wb/soft/2017/20170830/8895673712.apk";
        /**
         * 应用名称
         */
        mAppName = getResources().getString(R.string.app_name);
        mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mTask = new MyTask();
        mTask.execute(APP_UPDATE_URL);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 结束任务
     * @param task 要结束的异步任务
     */
    private void cancelTask(AsyncTask task) {
        task.cancel(true);
        showErrorNotification();
        DownloadService.this.stopSelf();

    }

    /**
     * 创建目录
     *
     * @param filePath 文件的完整路径
     */
    private void autoCreatePath(String filePath) {
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
    }

    class MyTask extends AsyncTask<String, Integer, Boolean> {

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (!MyTask.this.isCancelled()) {
                NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(DownloadService.this);
                Notification build = mBuilder.setTicker("正在下载")
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentText("已下载" + values[0] + "%")
                        .setContentTitle(mAppName)
                        .setProgress(100, values[0], false)
                        .build();
                mManager.notify(NOTIFICATION_ID, build);
            } else {
                showErrorNotification();
            }
        }

        @Override
        protected Boolean doInBackground(String... strings) {
            if (!MyTask.this.isCancelled()) {

                try {
                    mUrl = new URL(strings[0]);
                    mConnection = mUrl.openConnection();
                    mTotalLength = mConnection.getContentLength();
                    mInputStream = mConnection.getInputStream();

                    autoCreatePath(SAVE_PATH);

                    // 获取输出流
                    mFileOutputStream = new FileOutputStream(SAVE_PATH);
                    int len = 0;
                    int sum = 0;
                    byte[] bytes = new byte[1024];
                    while (-1 != (len = mInputStream.read(bytes))) {
                        mFileOutputStream.write(bytes, 0, len);
                        sum += len;
                        int current = sum * 100 / mTotalLength;
                        if (current % 4 == 0) {
                            publishProgress(current);
                        }
                    }
                } catch (MalformedURLException e) {
                    showErrorNotification();
                    cancelTask(MyTask.this);

                    e.printStackTrace();
                    return false;
                } catch (FileNotFoundException e) {
                    showErrorNotification();
                    cancelTask(MyTask.this);

                    e.printStackTrace();
                    return false;
                } catch (SSLException e) {
                    showErrorNotification();
                    cancelTask(MyTask.this);
                    e.printStackTrace();
                    return false;
                } catch (IOException e) {
                    showErrorNotification();
                    cancelTask(MyTask.this);
                    e.printStackTrace();
                    return false;
                } finally {
                    if (mInputStream != null) {
                        try {
                            mInputStream.close();
                        } catch (IOException e) {
                            showErrorNotification();
                            cancelTask(MyTask.this);
                            e.printStackTrace();
                        }
                    }
                    if (mFileOutputStream != null) {
                        try {
                            mFileOutputStream.close();
                        } catch (IOException e) {
                            showErrorNotification();
                            cancelTask(MyTask.this);
                            e.printStackTrace();
                        }
                    }
                }
                return true;

            } else {
                showErrorNotification();
                cancelTask(MyTask.this);
                return false;
            }
        }


        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            if (aBoolean) {
                showSuccessNotification();
            } else {
                showErrorNotification();
            }
            //关闭服务
            DownloadService.this.stopSelf();
        }
    }


    /**
     * 获取安装的意图
     *
     * @param apkFilepath 应用的真实保存路径
     * @return
     */
    private Intent getInstallIntent(String apkFilepath) {
        String apkType = "application/vnd.android.package-archive";
        Intent intent = new Intent(Intent.ACTION_VIEW);
        // 设置标志位
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(new File(apkFilepath)), apkType);
        return intent;
    }

    /**
     * 删除下载失败的临时文件
     *
     * @param filePath
     */
    private void deleteTmpFile(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            File file = new File(filePath);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    /**
     * 显示成功的通知
     */
    private void showSuccessNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        PendingIntent pendingIntent = PendingIntent.getActivity(
                this, 0, getInstallIntent(SAVE_PATH), PendingIntent.FLAG_UPDATE_CURRENT
        );
        Notification build = mBuilder.setTicker("完成下载")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentText("点击安装")
                .setContentTitle(mAppName + "下载完成")
                .setContentIntent(pendingIntent)
                .setAutoCancel(true)
                .build();
        mManager.notify(NOTIFICATION_ID, build);
    }

    /**
     * 显示失败的通知
     */
    private void showErrorNotification() {
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);
        Notification build = mBuilder.setTicker("下载失败")
                .setSmallIcon(R.mipmap.ic_launcher)

                .setContentTitle(mAppName + "下载失败")
                .setAutoCancel(true)
                .build();
        mManager.notify(NOTIFICATION_ID, build);
        deleteTmpFile(SAVE_PATH);
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值