Android 实现文件的下载

Android 实现文件的下载


文件的上传其实就是自己组合成Post表单的形式进行Http的Post发送,这一篇要实现的是文件的下载,其实下载文件与打开网页是一样的,打开网页是将内容显示出来,保存文件就是保存到文件中即可。
  实现的代码基本如下:
  代码
  public void downFile(String url, String path, String fileName) throws IOException { if (fileName == null || fileName == "") this.FileName = url.substring(url.lastIndexOf("/") + 1); else this.FileName = fileName; // 取得文件名,如果输入新文件名,则使用新文件名 URL Url = new URL(url); URLConnection conn = Url.openConnection(); conn.connect(); InputStream is = conn.getInputStream(); this.fileSize = conn.getContentLength();// 根据响应获取文件大小 if (this.fileSize <= 0) { // 获取内容长度为0 throw new RuntimeException("无法获知文件大小 "); } if (is == null) { // 没有下载流 sendMsg(Down_ERROR); throw new RuntimeException("无法获取文件"); } FileOutputStream FOS = new FileOutputStream(path + this.FileName); // 创建写入文件内存流,通过此流向目标写文件 byte buf[] = new byte[1024]; downLoadFilePosition = 0; int numread; while ((numread = is.read(buf)) != -1) { FOS.write(buf, 0, numread); downLoadFilePosition += numread } try { is.close(); } catch (Exception ex) { ; } }
  通过此代码就可以实现将内容保存到SD卡等设备上,当然要使用网络,必须得有网络的访问权限。这个需要自己添加,在这里不再添加!
  上面的代码没有实现进度条功能,如果要实现进度条功能,我现在考虑到的就是使用消息进行发送提示,首先实现一个消息。
  代码
  private Handler downloadHandler = new Handler() { // 用于接收消息,处理进度条 @Override public void handleMessage(Message msg) { // 接收到的消息,并且对接收到的消息进行处理 if (!Thread.currentThread().isInterrupted()) { switch (msg.what) { case DOWN_START: pb.setMax(fileSize); //设置开始长度 case DOWN_POSITION: pb.setProgress(downLoadFilePosition); // 设置进度 break; case DOWN_COMPLETE: Toast.makeText(DownLoadFileTest.this, "下载完成!", 1).show(); // 完成提示 break; case Down_ERROR: String error = msg.getData().getString("下载出错!"); Toast.makeText(DownLoadFileTest.this, error, 1).show(); break; } } super.handleMessage(msg); } };
  这样,在下载的时候只要发送相应的消息,即可有相应的提示!不再细写,希望对你的思路有帮助!在这里仅仅提供一个思路,如果你有更好的想法,欢迎交流!



//下载apk程序代码
protected File downLoadFile(String httpUrl) {
                // TODO Auto-generated method stub
                final String fileName = "updata.apk";
                File tmpFile = new File("/sdcard/update");
                if (!tmpFile.exists()) {
                        tmpFile.mkdir();
                }
                final File file = new File("/sdcard/update/" + fileName);

                try {
                        URL url = new URL(httpUrl);
                        try {
                                HttpURLConnection conn = (HttpURLConnection) url
                                                .openConnection();
                                InputStream is = conn.getInputStream();
                                FileOutputStream fos = new FileOutputStream(file);
                                byte[] buf = new byte[256];
                                conn.connect();
                                double count = 0;
                                if (conn.getResponseCode() >= 400) {
                                        Toast.makeText(Main.this, "连接超时", Toast.LENGTH_SHORT)
                                                        .show();
                                } else {
                                        while (count <= 100) {
                                                if (is != null) {
                                                        int numRead = is.read(buf);
                                                        if (numRead <= 0) {
                                                                break;
                                                        } else {
                                                                fos.write(buf, 0, numRead);
                                                        }

                                                } else {
                                                        break;
                                                }

                                        }
                                }

                                conn.disconnect();
                                fos.close();
                                is.close();
                        } catch (IOException e) {
                                // TODO Auto-generated catch block

                                e.printStackTrace();
                        }
                } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block

                        e.printStackTrace();
                }

                return file;
        }
//打开APK程序代码

private void openFile(File file) {
                // TODO Auto-generated method stub
                Log.e("OpenFile", file.getName());
                Intent intent = new Intent();
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                intent.setAction(android.content.Intent.ACTION_VIEW);
                intent.setDataAndType(Uri.fromFile(file),
                                "application/vnd.android.package-archive");
                startActivity(intent);
        }



安装:
String str = "/CanavaCancel.apk";
String fileName = Environment.getExternalStorageDirectory() + str;
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
startActivity(intent);
卸载:
Uri packageURI = Uri.parse("package:com.demo.CanavaCancel");  
Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);  
startActivity(uninstallIntent);

Environment拥有一些可以获取环境变量的方法
package:com.demo.CanavaCancel 这个形式是 package:程序完整的路径 (包名+程序名).

你可能感兴趣的:(thread,android)