Android development-Online installation of android_apk (source code sharing)

Source: Internet
Author: User

For online installation of android_apk, in addition to designing the Android client code, we also need to build the server code and simulate the online upgrade of Android software.

The Android client code is as follows.

MainActivity

Package com. example. f03_packmanager; import java. io. file; import java. util. concurrent. executionException; import android.net. uri; import android. OS. asyncTask; import android. OS. bundle; import android. app. activity; import android. app. alertDialog; import android. app. progressDialog; import android. content. dialogInterface; import android. content. intent; import android. content. dialogInterface. onClickListener; impor T android. util. log; import android. view. view; import android. widget. button; public class MainActivity extends Activity {// Add permission, private Button button, and private ProgressDialog to obtain network access and read/write sdcard permissions in the file list; // query the version Update Progress dialog box private String messagePath = "http: // 111.0.124.108: 8080/http/servlet/Install"; // obtain the URLprivate Message message of the version update; private PackUtiles packUtiles; // The encapsulation class private Aler that obtains information about the current version. TDialog. builder builder; // download the updated dialog box @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main); dialog = new ProgressDialog (MainActivity. this); dialog. setTitle ("prompt"); dialog. setMessage ("download ..... "); builder = new AlertDialog. builder (MainActivity. this); builder. setTitle ("download updates"); builder. setMessage ("do you want to download the latest version? "); Builder. setCancelable (false); // you cannot close the dialog box Indicating to download updates. findViewById (R. id. button1); packUtiles = new PackUtiles (MainActivity. this); button. setOnClickListener (new View. onClickListener () {@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubtry {message = new getapkurl(cmd.exe cute (messagePath ). get (); boolean flag = packUtiles. update (packUtiles. getVersion (), message. getVsersionCode (); Log. I ("tag", "------->" + flag); if (flag) {builder. setPositiveButton ("OK", new OnClickListener () {@ Overridepublic void onClick (DialogInterface arg0, int arg1) {// TODO Auto-generated method stubnew downloadapk(.exe cute (message. getApkUrl () ;}}); builder. setNegativeButton ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface arg0, int arg1) {// TODO Auto-generated method stub}); builder. create (). show () ;}} catch (InterruptedException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (ExecutionException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}});} // asynchronous task for obtaining version update information public class getAPKUrl extends AsyncTask <String, Void, Message >{@ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute (); dialog. show () ;}@ Overrideprotected Message doInBackground (String... params) {// TODO Auto-generated method stubreturn HttpUtiles. getMessage (params [0]) ;}@ Overrideprotected void onPostExecute (Message result) {// TODO Auto-generated method stubsuper. onPostExecute (result); dialog. dismiss () ;}} public class downLoadAPK extends AsyncTask <String, Void, Void >{@ Overrideprotected void onPreExecute () {// TODO Auto-generated method stubsuper. onPreExecute () ;}@ Overrideprotected Void doInBackground (String... params) {// TODO Auto-generated method stubString uri = HttpUtiles. downLoadApk (params [0]); Log. I ("TAG2", "-------->" + uri); // use the file path to install the specified version Uri uri2 = Uri. fromFile (new File (uri); Intent intent = new Intent (Intent. ACTION_VIEW); intent. setDataAndType (uri2, "application/vnd. android. package-archive "); startActivity (intent); return null ;}@ Overrideprotected void onPostExecute (Void result) {// TODO Auto-generated method stubsuper. onPostExecute (result );}}}

HttpUtiles obtains the server version information. One method is to obtain the version data in json format, and the other is to download the latest version to sdcard.

Package com. example. f03_packmanager; import java. io. file; import java. io. fileOutputStream; import java. io. IOException; import org. apache. http. httpResponse; import org. apache. http. client. clientProtocolException; import org. apache. http. client. httpClient; import org. apache. http. client. methods. httpPost; import org. apache. http. impl. client. defaultHttpClient; import org. apache. http. util. entityUtils; import org. json. JSONException; import org. json. JSONObject; import android. OS. environment; import android. util. log; public class HttpUtiles {// download version information, in the format of jsonpublic static Message getMessage (String path) {Message message = new Message (); HttpClient client = new DefaultHttpClient (); httpPost httpPost = new HttpPost (path); try {HttpResponse httpResponse = client.exe cute (httpPost); if (httpResponse. getStatusLine (). getStatusC Ode () == 200) {String json = EntityUtils. toString (httpResponse. getEntity (); try {JSONObject jsonObject = new JSONObject (json ). getJSONObject ("message"); message. setVsersionCode (jsonObject. getInt ("vsersionCode"); message. setApkUrl (jsonObject. getString ("apkUrl");} catch (JSONException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} catch (ClientProtocolException e) {// TODO Auto-generated catc H blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return message;} // download the specified version to the sdcard public static String downLoadApk (String path) {byte [] data = null; String uri = null; httpClient client = new DefaultHttpClient (); HttpPost httpPost = new HttpPost (path); FileOutputStream fileOutputStream = null; try {HttpResponse httpResponse = client.exe cute (httpPost); if (HttpResponse. getStatusLine (). getStatusCode () == 200) {data = EntityUtils. toByteArray (httpResponse. getEntity (); if (Environment. getExternalStorageState (). equals (Environment. MEDIA_MOUNTED) {File file = Environment. getExternalStorageDirectory (); String name = path. substring (path. lastIndexOf ("/") + 1, path. length (); fileOutputStream = new FileOutputStream (new File (file, name); fileOutputStream. write (data, 0, data. Length); uri = file. getAbsolutePath () + "/" + name ;}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke. printStackTrace ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace ();} finally {if (fileOutputStream! = Null) {try {fileOutputStream. close ();} catch (IOException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} Log. I ("HTTP", "-------->" + uri); return uri ;}}
Message class specifies the format of data returned

package com.example.f03_packmanager;public class Message {private int vsersionCode;private String apkUrl;public int getVsersionCode() {return vsersionCode;}public void setVsersionCode(int vsersionCode) {this.vsersionCode = vsersionCode;}public String getApkUrl() {return apkUrl;}public void setApkUrl(String apkUrl) {this.apkUrl = apkUrl;}@Overridepublic String toString() {return "Message [vsersionCode=" + vsersionCode + ", apkUrl=" + apkUrl+ "]";}}
PackUtilse obtains the current version of the software.
Package com. example. f03_packmanager; import android. content. context; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. content. pm. packageManager. nameNotFoundException; public class PackUtiles {private Context context; private PackageManager manager; private PackageInfo info; public PackUtiles (Context context) {// TODO Auto-generated constructor stubthis. context = Context; initDate ();} public void initDate () {manager = context. getPackageManager (); try {info = manager. getPackageInfo (context. getPackageName (), PackageManager. GET_ACTIVITIES);} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace () ;}} public int getVersion () {return info. versionCode;} public String getVersionName () {return info. versionName;} // compare the size of the local version and server version pub Lic boolean update (int oldVersion, int newVersion) {boolean flag = newVersion> oldVersion? True: false; return flag ;}}

Now the Android code has been compiled. Next we will introduce the server code. We need to import the json jar package in advance, note that when using all http addresses, remember to change them to the IP address of your laptop. In addition, do not forget to put the SDK apk to be updated under the webroot directory.

package com.login.install;import java.io.IOException;import java.io.PrintWriter;import java.util.HashMap;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONSerializer;public class Install extends HttpServlet {/** * Constructor of the object. */public Install() {super();}/** * Destruction of the servlet. <br> */public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. *  * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();Message message=new Message();message.setVsersionCode(2);message.setApkUrl("http://111.0.124.108:8080/http/F03_PackManager.apk");    Map<String, Object> map=new HashMap<String, Object>();    map.put("message", message);    out.print(JSONSerializer.toJSON(map));out.flush();out.close();}/** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */public void init() throws ServletException {// Put your code here}}



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.