Android開發之android_apk 線上安裝(原始碼分享)

來源:互聯網
上載者:User

     android_apk的線上安裝,除了要設計Android 用戶端的代碼外,還要搭建伺服器的代碼,模擬實現中Android軟體的線上升級。

     Android  用戶端的代碼如下。

     

    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;import android.util.Log;import android.view.View;import android.widget.Button;public class MainActivity extends Activity {// 先在檔案清單添加擷取網路存取權限和准許讀寫sdcard的permission;private Button button;private ProgressDialog dialog;// 查詢版本更新資訊的進度對話方塊private String messagePath = "http://111.0.124.108:8080/http/servlet/Install";// 擷取版本更新的URLprivate Message message;private PackUtiles packUtiles;// 擷取目前的版本資訊的封裝類private AlertDialog.Builder builder;// 下載更新的對話方塊@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dialog = new ProgressDialog(MainActivity.this);dialog.setTitle("提示");dialog.setMessage("download.....");builder = new AlertDialog.Builder(MainActivity.this);builder.setTitle("下載更新");builder.setMessage("是否下載最新的版本?");builder.setCancelable(false);// 設定不能隨意關閉提示下載更新的對話方塊button = (Button) this.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().execute(messagePath).get();boolean flag = packUtiles.update(packUtiles.getVersion(),message.getVsersionCode());Log.i("tag", "------->" + flag);if (flag) {builder.setPositiveButton("確定", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stubnew downLoadAPK().execute(message.getApkUrl());}});builder.setNegativeButton("取消", 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();}}});}// 擷取版本更新資訊的非同步任務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);//通過檔案路徑安裝指定版本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擷取伺服器的版本資訊,一個方法為以json格式擷取版本的資料,一個為下載最新的版本到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 {     //下載版本資訊,格式為jsonpublic static Message getMessage(String path) {Message message = new Message();HttpClient client = new DefaultHttpClient();HttpPost httpPost = new HttpPost(path);try {HttpResponse httpResponse = client.execute(httpPost);if(httpResponse.getStatusLine().getStatusCode()==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 catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}        return message;}//下載指定版本到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.execute(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類指定資料返回的格式

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擷取軟體當前的版本資訊
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;    }    //比較本地版本和伺服器的版本號碼的大小    public boolean update(int oldVersion,int newVersion){    boolean flag=newVersion>oldVersion?true:false;    return flag;    }}     

      到此Android的代碼就編寫完成了,下面我們來介紹一下伺服器端的代碼,事先要匯入json的jar包,另外一點注意的是所有的http地址在自己使用的時候都記得改成自己筆記本的ip地址,此外別忘了把要更新的軟體apk放在webroot目錄下。

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



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.