Android to download the file function method _android

Source: Internet
Author: User
Tags getmessage

This article describes the implementation of Android download file function of the complete sample code, for learning and research on Android programming is believed to have some help, especially for Android beginners have some reference value.

The full functional code is as follows:

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) {//file downloaded to local end MT
   Extview01.settext ("Download ..."); 
   strURL = Medittext01.gettext (). toString ();
   * * Obtain the name of the file to install the program * * * * 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.settex
   T ("");
  Mtextview01.settext ("Remote installer (Please enter URL)");
 }
  });
  /* Process download URL file Custom Function */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 (); /* Get the remote file/private void Getdatasource (String strpath) throws Exception {if (! 
  Urlutil.isnetworkurl (strpath)) {mtextview01.settext ("wrong url");
  else {/* gets url*/URL myurl = new URL (strpath);
  /* Create Connection * * URLConnection conn = myurl.openconnection ();
  Conn.connect ();
  /*inputstream Download File */InputStream is = Conn.getinputstream (); 
  if (is = = null) {throw new RuntimeException ("stream is null"); /* Create temp File/* Mytempfile = File.createtempfile (Filena, ".")
  +fileex);
  /* Get the station save case Path * * Currenttempfilepath = Mytempfile.getabsolutepath ();
  /* Write file to scratch disk * * 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);
/* Open File for installation * *  OpenFile (Mytempfile); 
  try {is.close (); 
  catch (Exception ex) {LOG.E (TAG, "error:" + ex.getmessage (), ex);
  }////////* Open file on phone method */private void OpenFile (file f) {Intent Intent = new Intent ();
  Intent.addflags (Intent.flag_activity_new_task);
  
  Intent.setaction (Android.content.Intent.ACTION_VIEW);
  /* Call GetMimeType () to obtain mimetype/String type = GetMimeType (f);
  /* Set Intent File and MimeType * * Intent.setdataandtype (Uri.fromfile (f), type); 
 StartActivity (Intent);
  }/* The Judge file MimeType method/private string GetMimeType (file f) {string type= "";
  String Fname=f.getname ();
  /* Get extension */String end=fname.substring (Fname.lastindexof (".") 
  
  +1,fname.length ()). toLowerCase (); /* Depending on the type of extension 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"; } elseif (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.packag 
  E-archive ";
  else {type= "*"; 
  */* If it cannot be opened directly, jump out of the list of software to the user to select */if (end.equals ("apk")) {} else {type + = "*"; 
 } return type; 
  }/* Custom Delete file method * * private void Delfile (String strfilename) {File MyFile = new file (strFileName); 
  if (myfile.exists ()) {myfile.delete (); }/* When the activity is in the OnPause state, change the TextView text state/protected void OnPause () {mTextView01 = (TextView) Findviewbyid (r.i
  D.MYTEXTVIEW1);
  Mtextview01.settext ("Download Successful");
 Super.onpause (); 
  }/* When the activity is in the Onresume state, delete the temporary file/protected void Onresume () {* * Delete the temporary file */delfile (Currenttempfilepath); 
 Super.onresume ();
 }
}

Readers can modify and refine the example to make it more in line with their own project needs.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.