Android implements the download file function

  • 2020-06-03 08:13:37
  • OfStack

This article describes the Android download file function of the complete example code, for learning and research android programming I believe it will be helpful, especially for Android beginners have a reference value.

The complete 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) 
  {
   //  The file will be downloaded to local end  
   mTextView01.setText(" In the download ...");
   strURL = mEditText01.getText().toString(); 
   /* Gets the file name of the program to be installed */
   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(" Remote installer ( Please enter the URL)");
  }
  });
 }
 
 /*  Deals with download URL File custom functions  */
 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 a remote file */ 
 private void getDataSource(String strPath) throws Exception 
 { 
  if (!URLUtil.isNetworkUrl(strPath)) 
  { 
  mTextView01.setText(" The wrong URL"); 
  } 
  else 
  { 
  /* achieve URL*/
  URL myURL = new URL(strPath);
  /* Create a connection */
  URLConnection conn = myURL.openConnection();
  conn.connect();
  /*InputStream  The download file */
  InputStream is = conn.getInputStream();
  if (is == null) 
  { 
   throw new RuntimeException("stream is null"); 
  } 
  /* Create temporary files */ 
  File myTempFile = File.createTempFile(fileNa, "."+fileEx);
  /* Get the station file path */
  currentTempFilePath = myTempFile.getAbsolutePath();
  /* Write the file to the temporary 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 the file for installation */
  openFile(myTempFile);
  try 
  { 
   is.close(); 
  } 
  catch (Exception ex) 
  { 
   Log.e(TAG, "error: " + ex.getMessage(), ex); 
  } 
  }
 }
  
 /*  Open the file on the 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 achieve MimeType */
  String type = getMIMEType(f);
  /*  Set up the intent the file with MimeType */
  intent.setDataAndType(Uri.fromFile(f),type);
  startActivity(intent); 
 }

 /*  Judge documents MimeType the method */
 private String getMIMEType(File f) 
 { 
  String type="";
  String fName=f.getName();
  /*  Get the 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";
  }
  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 it can't be opened directly, it pops out of the software list and gives the user a choice  */
  if(end.equals("apk")) 
  { 
  } 
  else 
  { 
  type += "/*"; 
  } 
  return type; 
 } 

 /* Custom delete file methods */
 private void delFile(String strFileName) 
 { 
  File myFile = new File(strFileName); 
  if(myFile.exists()) 
  { 
  myFile.delete(); 
  } 
 } 
 
 /* when Activity In a onPause state , To change the TextView Text state */
 protected void onPause()
 {
  mTextView01 = (TextView)findViewById(R.id.myTextView1);
  mTextView01.setText(" Download successful ");
  super.onPause();
 }

 /* when Activity In a onResume state , Delete temporary file */ 
 protected void onResume() 
 { 
  /*  Delete temporary file  */ 
  delFile(currentTempFilePath); 
  super.onResume(); 
 }
}

The reader can modify and improve this example to make it more suitable for their own project requirements.


Related articles: