android开发中文件下载并自动安装或选择打开

编程知识 更新时间:2023-04-17 17:41:01

最近一个项目中用到下载文件,下载完成后并提示用户选择打开。之前有做过自动更新(下载apk文件),但是现在下载的是office文件,所以要重新写了。

实现思路:

1.下载文件 (多线程下载及更新UI显示下载进度)

2.下载完成后:弹窗提示用户是否打开(这里我用的是原生的AlertDialog,如果嫌不好看,可以自定)

3.用户选择“打开”后,调用手机自带软件打开它

点击下载按钮开始下载文件:

long fileLength = 0;//下载的文件长度
long contentLength;//文件的总长度
private String filePath;//文件的保存路径
int len;
private DocAdapterHandler handler;
//点击下载文件
viewHolder.download.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        dialog = new ProgressDialog(context, R.style.dialog);
        dialog.setMessage("0%");
        dialog.setInverseBackgroundForced(false);
        dialog.show();
        Thread thread = new Thread() {
            public void run() {
                try {
                    downFile(UrlUtil.HOST_IMAGE_URL + mod.getPath(), mod.getFname());
                } catch (Exception e) {
                }
            }
        };
        thread.start();
    }
});
/**
 * @param urlString:文件的URL
 * @param fileName:文件名
 */
private void downFile(String urlString, String fileName) {
    HttpURLConnection urlConnection = null;
     filePath = Environment.getExternalStorageDirectory() + "/" + fileName;
    Log.e("******文件的保存路径", filePath);
    try {
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
            fileLength = file.length();
        }
        urlConnection = (HttpURLConnection) new URL(urlString).openConnection();
        urlConnection.setReadTimeout(10000);
        urlConnection.setConnectTimeout(10000);
        urlConnection.setRequestProperty("RANGE", "bytes=" + fileLength + "-");
        urlConnection.setRequestProperty("Charset", "UTF-8");
        urlConnection.connect();
        contentLength = urlConnection.getContentLength();
        if (fileLength < (contentLength < 0 ? 1 : contentLength)) {
            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fos = new FileOutputStream(filePath, fileLength > 0);
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) > 0) {
                fos.write(bytes, 0, len);
                fileLength += len;
                Message message1 = new Message();
                message1.what = 1;
                handler.sendMessage(message1);
            }
            fos.flush();
            fos.getFD().sync();
            fos.close();
            inputStream.close();
            Message message2 = new Message();
            message2.what = 2;
            handler.sendMessage(message2);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    if (urlConnection != null) {
        urlConnection.disconnect();
    }
}

Handler类

private class DocAdapterHandler extends Handler {
    public void handleMessage(Message msg) {
        if (!Thread.currentThread().isInterrupted()) {
            switch (msg.what) {
                case 0:
                    dialog.setMessage(contentLength + "%");
                    Log.i("********文件长度-:", contentLength + "");
                    break;
                case 1:
                    long x = (fileLength / contentLength * 100);
                    dialog.setMessage(x + "%");
                    break;
                case 2:
                    dialog.dismiss();
                    Toast.makeText(context.getApplicationContext(), "下载完成", Toast.LENGTH_LONG).show();
                    MediaPlayerUtil.startOK();
                    AlertDialog.Builder builder = new AlertDialog.Builder(context);
                    builder.setTitle("下载完成");
                    builder.setNegativeButton("取消", null);
                    builder.setPositiveButton("打开", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            File file = new File(filePath);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.setAction(Intent.ACTION_VIEW);
                            String type = getMIMEType(file);
                            //设置intent的data和Type属性。
                            intent.setDataAndType(Uri.fromFile(file), type);
                            try {
                                context.startActivity(intent);
                            } catch (ActivityNotFoundException e) {
                                Toast.makeText(context, "您没有安装Office文件", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                    builder.show();
                    break;
            }
        }
    }
}
/**
 * 根据文件后缀名匹配MIMEType
 *
 * @param file
 * @return
 */
public static String getMIMEType(File file) {
    String type = "*/*";
    String name = file.getName();
    int index = name.lastIndexOf('.');
    if (index < 0) {
        return type;
    }
    String end = name.substring(index, name.length()).toLowerCase();
    if (TextUtils.isEmpty(end)) return type;

    for (int i = 0; i < MIME_MapTable.length; i++) {
        if (end.equals(MIME_MapTable[i][0]))
            type = MIME_MapTable[i][1];
    }
    return type;
}

private static final String[][] MIME_MapTable = {
        {".3gp", "video/3gpp"},
        {".apk", "application/vnd.android.package-archive"},
        {".asf", "video/x-ms-asf"},
        {".avi", "video/x-msvideo"},
        {".bin", "application/octet-stream"},
        {".bmp", "image/bmp"},
        {".c", "text/plain"},
        {".class", "application/octet-stream"},
        {".conf", "text/plain"},
        {".cpp", "text/plain"},
        {".doc", "application/msword"},
        {".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
        {".xls", "application/vnd.ms-excel"},
        {".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
        {".exe", "application/octet-stream"},
        {".gif", "image/gif"},
        {".gtar", "application/x-gtar"},
        {".gz", "application/x-gzip"},
        {".h", "text/plain"},
        {".htm", "text/html"},
        {".html", "text/html"},
        {".jar", "application/java-archive"},
        {".java", "text/plain"},
        {".jpeg", "image/jpeg"},
        {".jpg", "image/jpeg"},
        {".js", "application/x-javascript"},
        {".log", "text/plain"},
        {".m3u", "audio/x-mpegurl"},
        {".m4a", "audio/mp4a-latm"},
        {".m4b", "audio/mp4a-latm"},
        {".m4p", "audio/mp4a-latm"},
        {".m4u", "video/vnd.mpegurl"},
        {".m4v", "video/x-m4v"},
        {".mov", "video/quicktime"},
        {".mp2", "audio/x-mpeg"},
        {".mp3", "audio/x-mpeg"},
        {".mp4", "video/mp4"},
        {".mpc", "application/vnd.mpohun.certificate"},
        {".mpe", "video/mpeg"},
        {".mpeg", "video/mpeg"},
        {".mpg", "video/mpeg"},
        {".mpg4", "video/mp4"},
        {".mpga", "audio/mpeg"},
        {".msg", "application/vnd.ms-outlook"},
        {".ogg", "audio/ogg"},
        {".pdf", "application/pdf"},
        {".png", "image/png"},
        {".pps", "application/vnd.ms-powerpoint"},
        {".ppt", "application/vnd.ms-powerpoint"},
        {".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
        {".prop", "text/plain"},
        {".rc", "text/plain"},
        {".rmvb", "audio/x-pn-realaudio"},
        {".rtf", "application/rtf"},
        {".sh", "text/plain"},
        {".tar", "application/x-tar"},
        {".tgz", "application/x-compressed"},
        {".txt", "text/plain"},
        {".wav", "audio/x-wav"},
        {".wma", "audio/x-ms-wma"},
        {".wmv", "audio/x-ms-wmv"},
        {".wps", "application/vnd.ms-works"},
        {".xml", "text/plain"},
        {".z", "application/x-compress"},
        {".zip", "application/x-zip-compressed"},
        {"", "*/*"}
};


运行效果:




OK,到此就结束了!最后再奉献上如果是自动更新apk时的代码:

/**
 * 自动安装apk文件
 * @param context
 * @param file
 */
public static void openApk(Context context,File file) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
    context.startActivity(intent);
}

更多推荐

android开发中文件下载并自动安装或选择打开

本文发布于:2023-04-14 02:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/b0d52cc2659b28d64f87c98c4c7d7aee.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:文件   android

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 74286文章数
  • 14阅读数
  • 0评论数