Android Download apk install APK open apk

Source: Internet
Author: User

Today there is a need to download an apk file, and then when you are done downloading, the text of the button changes, becomes the click Install, and then after the installation is completed, it turns on.

Here's how to download apk:

/** * Backstage in the following apk download completed after downloading the file * * @param httpurl * @return */private file downfile (final String httpurl) {New Thread (new Runnable () {@Overridepublic 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 () = =) {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.WR ITE (buffer, 0, length);} Fileoutputstream.close (); Fileoutputstream.flush ();} Inputstream.close ();} System.out.println ("already downloaded");//Send a message to handler change the Text property of the button message message = Handler.obtainmessage (); Message.what = 1;handler.sendmessage (message);} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}}). Start (); return file;}


Here's how to install the APK:

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


Here's how to open the APK:

/** * Open the installed apk */private void openapk (context context, String URL) {Packagemanager manager = Context.getpackagemanager ( )///Here is the file path you downloaded PackageInfo info = manager.getpackagearchiveinfo (environment.getexternalstoragedirectory (). GetAbsolutePath () + getfilepath (URL), packagemanager.get_activities); if (info! = null) {Intent Intent = Manager.getlaunchintentforpackage (Info.applicationInfo.packageName); startactivity (intent);}}
Open apk here for a long time, didn't know there is a Getlaunchintentforpackage method this method as long as you can get this apk registration, and then add the package name to the back, startactivity it will automatically automatically your APK main interface. Believe to get an apk of the information This everyone will, here will not say.


Here is all my code:

/** * Download apk install APK open apk * * @author Administrator * */public class Mainactivity extends Activity {private Button button1 ;p rivate static final String url_string = "http://gdown.baidu.com/data/wisegame/b7d7e4efd8199dea/tianyiyuedu_310.apk ";p rivate static int down = 0; File file;private Handler Handler = new Handler () {@Overridepublic void Handlemessage (Message msg) {Super.handlemessage (M SG), switch (msg.what) {Case 1:button1.settext ("click Install");d own = 1;break;case 2:down = 2;button1.settext ("open"); break;}}; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main) button1 = (Button) Findviewbyid (R.id.button1); Button1.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {//download apkif (down = = 0) {downfile (url_string); Button1.settext (" Downloading ");//install APK} else if (down = = 1) {installapk ();//Open APK} else if (down = = 2) {openapk (mainactivity.this, url_string);} }});} Receive the installation complete APK broadcast broadcastreceiver BROadcastreceiver = new Broadcastreceiver () {@Overridepublic void OnReceive (context context, Intent Intent) { SYSTEM.OUT.PRINTLN ("Receive a broadcast of the installation Complete apk"); Message message = Handler.obtainmessage (); message.what = 2;handler.sendmessage (message);}};/ * * Background in the following apk download completed after downloading the good file * * @param httpurl * @return */private file downfile (final String httpurl) {New Thread (new Runnable () {@Overridepublic 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 () = =) {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.WR ITE (buffer, 0, length);} Fileoutputstream.close (); fileoutputstream.flUsh ();} Inputstream.close ();} System.out.println ("already downloaded");//Send a message to handler change the Text property of the button message message = Handler.obtainmessage (); Message.what = 1;handler.sendmessage (message);} catch (Malformedurlexception e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}}). Start (); return file;} /** * Install apk */private void installapk () {Intent Intent = new Intent (Intent.action_view); Intent.setdataandtype ( Uri.fromfile (file), "application/vnd.android.package-archive"); StartActivity (intent);} @Overrideprotected void OnStart () {Super.onstart (); Intentfilter intentfilter = new Intentfilter (); Intentfilter.addaction (intent.action_package_added); Intentfilter.adddatascheme ("package");// Register a broadcast registerreceiver (Broadcastreceiver, intentfilter);} @Overrideprotected void OnDestroy () {Super.ondestroy ();//de-broadcast unregisterreceiver (broadcastreceiver);} /** * Open the installed apk */private void openapk (context context, String URL) {Packagemanager manager = Context.getpackagemanager ( )///Here is your download good file path PackageInfo info = Manager.getpackagearchiveinfo (environment.getexternalstoragedirectory (). GetAbsolutePath () + getFilePath (url ), packagemanager.get_activities), if (info! = null) {Intent Intent = Manager.getlaunchintentforpackage ( Info.applicationInfo.packageName); startactivity (intent);}} /** * Creates a file based on the URL that is passed in * */private files getFile (String url) {File files = new file (Environment.getexternalstoragedirectory (). Getabsolutefile (), GetFilePath (URL)); return files;} /** * intercepts the filename of the apk following the URL * * @param URL * @return */private string getfilepath (string url) {return url.substring (url.lastin Dexof ("/"), Url.length ());}}


The layout file is just a button and is not posted. There is one more thing that is listening to a broadcast of an app installation, and I'm here to register directly in the code:

Intentfilter filter = new Intentfilter ();            Filter.addaction ("Android.intent.action.PACKAGE_ADDED");      Filter.addaction ("Android.intent.action.PACKAGE_REMOVED");      Filter.adddatascheme ("package");

Listen to install apk and uninstall the APK broadcast, others believe you can see the code also understand, the code is a bit rough (rookie a), where the bad place to write, welcome to correct.

This program I did not consider other situations, such as APK installation error, how to deal with, and so on.


Forgot to say, also need to add in the configuration file access to the network and write files to the SD card permissions:

<uses-permission android:name= "Android.permission.INTERNET"/>    <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>


of the source code


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.