当前位置: 移动技术网 > IT编程>移动开发>Android > Android实现下载文件功能的方法

Android实现下载文件功能的方法

2019年07月24日  | 移动技术网IT编程  | 我要评论

世界城市gdp,色行天下,手抄报红领巾心向党

本文所述为android实现下载文件功能的完整示例代码,对于学习和研究android编程相信会有一定的帮助,尤其是对android初学者有一定的借鉴价值。

完整功能代码如下:

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(); 
 }
}

读者可以在该实例的基础上进行修改与完善,使之更符合自身项目需求。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网