Introduction to the method of downloading and automatic installation of apk in Android

Source: Internet
Author: User
Tags file size sendmsg stub

Mobile phone file download is divided into the background of automatic download and foreground download, I summed up the implementation of these two code, where the foreground download and realize the download progress bar implementation.


The first type: Background download

/**
* Background in the following one apk download completed to return the downloaded file
*
* @param httpurl
* @return
*/
Private File downfile (final String httpurl) {

New Thread (New Runnable () {

@Override
public void Run () {
try {
URL url = new URL (httpurl);
HttpURLConnection connection = (httpurlconnection) url.openconnection ();
Connection.setrequestmethod ("get");
Connection.setconnecttimeout (5000);
FileOutputStream fileoutputstream = null;
InputStream InputStream;
if (connection.getresponsecode () = = 200) {
InputStream = Connection.getinputstream ();

if (InputStream!= null) {
File = GetFile (Httpurl);
FileOutputStream = new FileOutputStream (file);
byte[] buffer = new byte[1024];
int length = 0;

while (length = inputstream.read (buffer))!=-1) {
Fileoutputstream.write (buffer, 0, length);
}
Fileoutputstream.close ();
Fileoutputstream.flush ();
}
Inputstream.close ();
}
Download complete
Installation
INSTALLAPK ();
catch (Malformedurlexception e) {
E.printstacktrace ();
catch (IOException e) {
E.printstacktrace ();
}
}
). Start ();
return file;
}

/**
* Create a file based on the URL sent over
*
*/
Private File getFile (String URL) {
File files = new file (Environment.getexternalstoragedirectory (). Getabsolutefile (), GetFilePath (URL));
return files;
}


/**
* intercepts the filename of the apk after the URL
*
* @param URL
* @return
*/
private string GetFilePath (string url) {
Return url.substring (Url.lastindexof ("/"), Url.length ());
}

/**
* Install APK
*/
private void installapk () {
Intent Intent = new Intent (Intent.action_view);
Intent.setdataandtype (uri.fromfile (file), "application/vnd.android.package-archive");
StartActivity (Intent);
}

Second Kind

Download APK program code
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, "Connection timeout", 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;
}
Open APK Program code

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

The above method directly calls the Downfile methods, the parameters pass a URL address can be

The third type:

Private String url= "http://----------------------. apk";
private file file;
Private ProgressBar PB;
Private TextView TV;
private int fileSize;
private int downloadfilesize;
private String filename;
Private Handler Handler = new Handler () {
@Override
public void Handlemessage (message msg) {//define a handler that handles the communication between the download thread and the UI
if (! Thread.CurrentThread (). isinterrupted ()) {
Switch (msg.what) {
Case 0:
Pb.setmax (fileSize);
Case 1:
Pb.setprogress (downloadfilesize);
int result = Downloadfilesize * 100/filesize;
Tv.settext (Result + "%");
Break
Case 2:
Finish ();
OpenFile (file);
Break
Case-1:
String error = Msg.getdata (). getString ("error");
Toast.maketext (downloadactivity.this, Error, Toast.length_short). Show ();
Break
}
}
Super.handlemessage (msg);
}
};
New Thread () {
public void Run () {
try {
Down_file (URL, "/sdcard/");
Download files, parameters: first URL, second store path
catch (Clientprotocolexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
catch (IOException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
}.start ();
public void Down_file (string url, string path) throws IOException {//download function
filename = url.substring (Url.lastindexof ("/") + 1)//Get filename
URL myurl = new URL (URL);
URLConnection conn = Myurl.openconnection ();
Conn.connect ();
InputStream is = Conn.getinputstream ();
This.filesize = Conn.getcontentlength ()//Get file size based on response
if (this.filesize <= 0) throw new RuntimeException ("Unable to learn file size");
if (is = = null) throw new RuntimeException ("stream is null");
FileOutputStream fos = new FileOutputStream (path + filename);//Save data to path + filename

byte buf[] = new byte[1024];
downloadfilesize = 0;
sendmsg (0);
do {
Looping read
int numread = Is.read (BUF);
if (Numread = = 1) {
Break
}
Fos.write (buf, 0, Numread);
Downloadfilesize + = Numread;
Sendmsg (1);//Update progress bar
} while (true);
File = new file (path + filename);
Sendmsg (2);//Notify Download complete
try {
Is.close ();
catch (Exception ex) {
LOG.E ("tag", "Error:" + ex.getmessage (), ex);
}
}

private void sendmsg (int flag) {
msg = new Message ();
Msg.what = Flag;
Handler.sendmessage (msg);
}
Open APK Program code

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

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.