Today, you have a need to download an apk file. After the download is complete, the text of the button changes to click Install. After the installation is complete, the button changes to open.
Here is how to download the apk:
/*** Return the downloaded File after the following Apk is downloaded in the background. ** @ 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 () = 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 ();} System. out. println ("downloaded"); // send a Message to handler to change the text attribute of the button. message = handler. obtainMessage (); message. what = 1; handler. sendMessage (message);} catch (MalformedURLException e) {e. printStackTrace ();} catch (IOException e) {e. printStackTrace ();}}}). start (); return file ;}
Here is how to install 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 is how to open the APK:
/*** Open the installed apk */private void openApk (Context context, String url) {PackageManager manager = context. getPackageManager (); // The downloaded file path PackageInfo = manager. getPackageArchiveInfo (Environment. getExternalStorageDirectory (). getAbsolutePath () + getFilePath (url), PackageManager. GET_ACTIVITIES); if (info! = Null) {Intent intent = manager. getLaunchIntentForPackage (info. applicationInfo. packageName); startActivity (intent );}}
It took a long time to open the APK. I didn't know there was a getLaunchIntentForPackage method before. As long as you can get the apk registration, add the package name to the end, startActivity automatically displays the main interface of your APK. I believe everyone will get the information of an APK. I won't talk about it here.
Below are all my codes:
/*** Download Apk install Apk open APK *** @ author Administrator **/public class MainActivity extends Activity {private Button button1; private static final String URL_STRING = "http://gdown.baidu.com/data/wisegame/b7d7e4efd8199dea/tianyiyuedu_310.apk "; private static int down = 0; File file; private Handler handler = new Handler () {@ Overridepublic void handleMessage (Message msg) {super. handleMessage (msg); switch (MS G. what) {case 1: button1.setText ("click to install"); down = 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) {down File (URL_STRING); button1.setText ("downloading"); // install APK} else if (down = 1) {installApk (); // open apk} else if (down = 2) {openApk (MainActivity. this, URL_STRING) ;}}) ;}// receives the broadcast BroadcastReceiver broadcastReceiver = new BroadcastReceiver () {@ Overridepublic void onReceive (Context context, Intent intent) after the apk is installed) {System. out. println ("broadcast of installed apk received"); Message message = handler. obtainMessage (); message. what = 2; h Andler. sendMessage (message );}}; /*** return the downloaded File after the following Apk is downloaded in the background. ** @ 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 () == 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 ();} System. out. println ("downloaded"); // send a Message to handler to change the text attribute of the button. 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 registerRe Ceiver (broadcastReceiver, intentFilter);} @ Overrideprotected void onDestroy () {super. onDestroy (); // unregisterReceiver (broadcastReceiver);}/*** open the installed apk */private void openApk (Context context, String url) {PackageManager manager = context. getPackageManager (); // The downloaded file path PackageInfo = manager. getPackageArchiveInfo (Environment. getExternalStorageDirectory (). getAbsolutePath () + getFileP Ath (url), PackageManager. GET_ACTIVITIES); if (info! = Null) {Intent intent = manager. getLaunchIntentForPackage (info. applicationInfo. packageName); startActivity (intent) ;}}/*** create a File based on the uploaded url **/private File getFile (String url) {File files = new File (Environment. getExternalStorageDirectory (). getAbsoluteFile (), getFilePath (url); return files ;} /*** extract the apk file name after the url ** @ param url * @ return */private String getFilePath (String url) {return url. substring (url. lastIndexOf ("/"), url. length ());}}
The layout file does not need to be pasted with a button. Another thing is to listen to the broadcast after an application is installed. Here I register it 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 the apk installation and uninstall the apk broadcast. Others believe that you can understand the code as well. The code is a bit rough (one for cainiao). You can tell me where the code is not well written.
I did not consider other cases, such as apk installation errors, how to handle them, and so on ..
If you forget to mention it, you also need to add the permissions to access the network and write files to the SD card in the configuration file:
Source code