Android下载文件

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Main extends Activity {
 
    private TextView mTextView01;
    private EditText mEditText01;
    private Button mButton01;
    private static final String TAG = "DOWNLOADAPK";
    private String currentFilePath = "";
    private String currentTempFilePath = "";
    private String strURL="";
    private String fileEx="";
    private String fileNa="";
   
    public void onCreate(Bundle savedInstanceState)
    {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      
      mTextView01 = (TextView)findViewById(R.id.myTextView1);
      mButton01 = (Button)findViewById(R.id.myButton1);
      mEditText01 =(EditText)findViewById(R.id.myEditText1);
  
      mButton01.setOnClickListener(new Button.OnClickListener()
      {
        public void onClick(View v)
        {
          /* 文件会下载至local端 */
          mTextView01.setText("下载中...");
          strURL = mEditText01.getText().toString();
          /*取得欲安装程序之文件名称*/
          fileEx = strURL.substring(strURL.lastIndexOf(".")
          +1,strURL.length()).toLowerCase();
          fileNa = strURL.substring(strURL.lastIndexOf("/")
          +1,strURL.lastIndexOf("."));
          getFile(strURL);
         }
       }
      );
     
      mEditText01.setOnClickListener(new EditText.OnClickListener()
      {

        public void onClick(View arg0){
          mEditText01.setText("");
          mTextView01.setText("远程安装程序(请输入URL)");
        }
      });
    }
   
    /* 处理下载URL文件自定义函数 */
    private void getFile(final String strPath)  {
      try
      {
        if (strPath.equals(currentFilePath) )
        {
          getDataSource(strPath);
        }
        currentFilePath = strPath;
        Runnable r = new Runnable()
        {
          public void run()
          {
            try
            {
              getDataSource(strPath);
            }
            catch (Exception e)
            {
              Log.e(TAG, e.getMessage(), e);
            }
          }
        };
        new Thread(r).start();
      }
      catch(Exception e)
      {
        e.printStackTrace();
      }
    }
   
     /*取得远程文件*/
    private void getDataSource(String strPath) throws Exception
    {
      if (!URLUtil.isNetworkUrl(strPath))
      {
        mTextView01.setText("错误的URL");
      }
      else
      {
        /*取得URL*/
        URL myURL = new URL(strPath);
        /*创建连接*/
        URLConnection conn = myURL.openConnection();
        conn.connect();
        /*InputStream 下载文件*/
        InputStream is = conn.getInputStream();
        if (is == null)
        {
          throw new RuntimeException("stream is null");
        }
        /*创建临时文件*/
        File myTempFile = File.createTempFile(fileNa, "."+fileEx);
        /*取得站存盘案路径*/
        currentTempFilePath = myTempFile.getAbsolutePath();
        /*将文件写入暂存盘*/
        FileOutputStream fos = new FileOutputStream(myTempFile);
        byte buf[] = new byte[128];
        do
        {
          int numread = is.read(buf);
          if (numread <= 0)
          {
            break;
          }
          fos.write(buf, 0, numread);
        }while (true);
       
        /*打开文件进行安装*/
        openFile(myTempFile);
        try
        {
          is.close();
        }
        catch (Exception ex)
        {
          Log.e(TAG, "error: " + ex.getMessage(), ex);
        }
      }
    }
    
    /* 在手机上打开文件的method */
    private void openFile(File f)
    {
      Intent intent = new Intent();
      intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
      intent.setAction(android.content.Intent.ACTION_VIEW);
     
      /* 调用getMIMEType()来取得MimeType */
      String type = getMIMEType(f);
      /* 设置intent的file与MimeType */
      intent.setDataAndType(Uri.fromFile(f),type);
      startActivity(intent);
    }

    /* 判断文件MimeType的method */
    private String getMIMEType(File f)
    {
      String type="";
      String fName=f.getName();
      /* 取得扩展名 */
      String end=fName.substring(fName.lastIndexOf(".")
      +1,fName.length()).toLowerCase();
     
      /* 依扩展名的类型决定MimeType */
      if(end.equals("m4a")||end.equals("mp3")||end.equals("mid")||
      end.equals("xmf")||end.equals("ogg")||end.equals("wav"))
      {
        type = "audio";
      }
      else if(end.equals("3gp")||end.equals("mp4"))
      {
        type = "video";
      }
      else if(end.equals("jpg")||end.equals("gif")||end.equals("png")||
      end.equals("jpeg")||end.equals("bmp"))
      {
        type = "image";
      }
      else if(end.equals("apk"))
      {
        /* android.permission.INSTALL_PACKAGES */
        type = "application/vnd.android.package-archive";
      }
      else
      {
        type="*";
      }
      /*如果无法直接打开,就跳出软件列表给用户选择 */
      if(end.equals("apk"))
      {
      }
      else
      {
        type += "/*"; 
      }
      return type; 
    }

    /*自定义删除文件方法*/
    private void delFile(String strFileName)
    {
      File myFile = new File(strFileName);
      if(myFile.exists())
      {
        myFile.delete();
      }
    }
   
    /*当Activity处于onPause状态时,更改TextView文字状态*/
    protected void onPause()
    {
      mTextView01 = (TextView)findViewById(R.id.myTextView1);
      mTextView01.setText("下载成功");
      super.onPause();
    }

    /*当Activity处于onResume状态时,删除临时文件*/
    protected void onResume()
    { 
      /* 删除临时文件 */
      delFile(currentTempFilePath);
      super.onResume();
    }
}

转载于:https://my.oschina.net/u/614562/blog/228806

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/291452.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

C++之operator关键字(重载操作符) 使用总结

operator是C++的关键字,它和运算符一起使用,表示一个运算符函数, 一、为什么使用操作符重载 简单的说我们基本数据比如int float 都可以比较大小 有>、<、=,但是对象需要比较大小怎么办,我们也可以用>、<、=,只不过我们需要一个通用的规范比较对象的属性…

#HTTP协议学习# (七)cookie

本文转自&#xff1a;http://www.cnblogs.com/TankXiao/archive/2012/12/12/2794160.html Cookie是HTTP协议中非常重要的东西&#xff0c; 之前拜读了Fish Li 写的【细说Cookie】&#xff0c; 让我学到了很多东西。Fish的这篇文章写得太经典了。 所以我这篇文章就没有太多内容了…

C#中的类型~存储~变量

欢迎您成为我的读者&#xff0c;希望这篇文章能给你一些帮助。前言今天在群里看到朋友讨论把粉丝称为读者&#xff0c;这让我内心特别激动。以前我还是比较关注自己的文章阅读量&#xff0c;有没有人转发&#xff0c;今天新增多少个关注。而现在&#xff0c;我的关注点变了&…

sql-逻辑循环while if

--计算1-100的和declare int int1;declare total int0;while(int<100)beginset totaltotalint;set intint 1;endselect total--计算1-100偶数的和declare index int;declare sum int;set index1;set sum0;while(index<100)beginif(index%20)beginset sumsumindexendset i…

mysql常用cmd指令_Mysql cmd 常用命令

连接&#xff1a;mysql -h主机地址 -u用户名 &#xff0d;p用户密码 (注:u与root可以不用加空格&#xff0c;其它也一样)断开&#xff1a;exit (回车)创建授权&#xff1a;grant select on 数据库.* to 用户名登录主机 identified by \"密码\"修改密码&#xff1a;my…

C++之typename

1、typename和class 在模板前,typename和class没有区别 template<typename T> class A; template<class T> class A;typename和class对编译器而言却是不同的东西 2、声明一个类型 看下面的代码 我们编译下结果如下 编译器不知道T::const_iterator是个类型。如果…

ubuntu 的QT4的qmake失败的处理方法

安装qt4以后使用命令行编译时出现一下错误&#xff1a;administratorubuntu:~/qt/qt-book/chap01/hello$ qmake hello.pro程序 qmake 已包含在以下软件包中&#xff1a;* qt3-dev-tools* qt4-qmake试试&#xff1a;sudo apt-get install <选定的软件包>bash: qmake&#…

gulp与webpack的区别

常有人拿gulp与webpack来比较&#xff0c;知道这两个构建工具功能上有重叠的地方&#xff0c;可单用&#xff0c;也可一起用&#xff0c;但本质的区别就没有那么清晰。 gulp gulp强调的是前端开发的工作流程&#xff0c;我们可以通过配置一系列的task&#xff0c;定义task处理的…

mooc数据结构与算法python版期末考试_数据结构与算法Python版-中国大学mooc-试题题目及答案...

数据结构与算法Python版-中国大学mooc-试题题目及答案更多相关问题婴儿出生一两天后就有笑的反应&#xff0c;这种笑的反应属于()。【判断题】填制原始凭证&#xff0c;汉字大写金额数字一律用正楷或草书书写&#xff0c;汉字大写金额数字到元位或角位为止的&#xff0c;后面必…

使用 NetCoreBeauty 优化 .NET CORE 独立部署目录结构

在将一个 .NET CORE \ .NET 5.0 \ .NET 6.0 程序进行独立部署发布时&#xff0c;会在发布目录产生很多系统类库&#xff0c;导致目录非常不简洁。这给寻找入口程序造成了困难&#xff0c;特别是路遥工具箱这种绿色软件&#xff0c;不会在开始菜单、系统桌面创建快捷方式&#x…

关于注释

在编写程序时&#xff0c;应当给程序添加一些注释&#xff0c;用于说明某段代码的作用&#xff0c;或者说明某个类的用途&#xff0c;某个方法的功能&#xff0c;以及该方法的参数和返回值类型和意义等。 很多初学者开始学习编程语言时&#xff0c;会很努力写程序&#xff0c;但…

从此不再惧怕URI编码:JavaScript及C# URI编码详解

混乱的URI编码 JavaScript中编码有三种方法:escape、encodeURI、encodeURIComponent C#中编码主要方法&#xff1a;HttpUtility.UrlEncode、Server.UrlEncode、Uri.EscapeUriString、Uri.EscapeDataString JavaScript中的还好&#xff0c;只提供了三个&#xff0c;C#中主要用的…

ios之最简单的程序

1、构建学生对象并且打印相关信息 代码&#xff1a;#import <UIKit/UIKit.h> #import "AppDelegate.h"interface Student : NSObject //变量 property NSString *name; property int age; property float score;//method -(void)show;endimplementation Studen…

网站前端_EasyUI.基础入门.0009.使用EasyUI Layout组件的最佳姿势?

1. 基础布局<div id"l" class"easyui-layout" data-options"width:500,height:250"><div data-options"region:north,title:north,height:50"></div><div data-options"region:west,title:west,width:100&q…

MySQL数据库如何管理与维护_mysql数据库的管理与维护

mysql数据库的管理与维护云服务器(Elastic Compute Service&#xff0c;简称ECS)是阿里云提供的性能卓越、稳定可靠、弹性扩展的IaaS(Infrastructure as a Service)级别云计算服务。云服务器ECS免去了您采购IT硬件的前期准备&#xff0c;让您像使用水、电、天然气等公共资源一样…

[转载]Javascript异步编程的4种方法

NodeJs的最大特性就是"异步" 目前在NodeJs里实现异步的方法中&#xff0c;使用“回调”是最常见的。 其实还有其他4种实现异步的方法&#xff1a; 在此以做记录 --- http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html --- 你可能知道&am…

继 SpringBoot 3.0,Elasticsearch8.0 官宣:拥抱 Java 17

大家好&#xff0c;我是君哥。新版任你发&#xff0c;我用 Java 8&#xff0c;这可能是当下 Java 开发者的真实写照。不过时代可能真的要抛弃 Java 8&#xff0c;全面拥抱 Java 17 了。Spring Boot 3.0前些天&#xff0c;相信小伙伴们都注意到了&#xff0c;SpringBoot 发布了 …

文件下载

2019独角兽企业重金招聘Python工程师标准>>> public String downloadFile() {try {if (id ! null && !"".equals(id) && !"null".equals(id)) {ResourceFile rf resourceFile.getResourceFile(id);filename new String(rf.ge…

ios之Xcode工程中添加文件常用快捷键

1、Xcode某个工程中添加文件 有两种方式&#xff1a; 方式一&#xff1a;“command”&#xff0b;“n”&#xff0c;弹出添加文件对话框。 方式二&#xff1a;在需要添加文件的工程目录下右键&#xff0c;选择“New File…”。 以上方式Xcode会弹出下面的对话框&#xff1…

递归-字符串翻转

代码&#xff1a; #include <iostream> #include <string>using namespace std;string F(string _str) {if(_str.length() < 1) return _str;return F(_str.substr(1)) _str.at(0); }int main() {string str "ABCDEF";cout << F(str);return …