Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 開發實作:android_apk 在線安裝(源碼分享)

編輯:關於 Android 程式設計

要實現 Android 應用的在線安裝(即軟體的在線升級),除了要撰寫 Android 客戶端程式碼,還需要搭建一個服務器端,模擬並驅動整個升級流程。本文完整分享這套實作的源碼。

Android 客戶端的主要程式碼如下。

MainActivity

先在清單檔中加上網路訪問權限與讀寫 sdcard 的權限。整體流程為:查詢版本更新資訊 → 比較本地與伺服器版本 → 提示下載 → 下載並觸發安裝。

package com.example.f03_packmanager;

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 {
    private Button button;
    private ProgressDialog dialog; // 查詢版本更新資訊的進度對話框
    private String messagePath = "https://111.0.124.108:8080/http/servlet/Install"; // 獲取版本更新的 URL
    private Message message;
    private PackUtiles packUtiles; // 獲取當前版本資訊的封裝類
    private AlertDialog.Builder builder; // 下載更新的對話框

    @Override
    protected 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() {
            @Override
            public void onClick(View v) {
                try {
                    message = new getAPKUrl().execute(messagePath).get();
                    boolean flag = packUtiles.update(packUtiles.getVersion(), message.getVsersionCode());
                    if (flag) {
                        builder.setPositiveButton("確定", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                new downLoadAPK().execute(message.getApkUrl());
                            }
                        });
                        builder.setNegativeButton("取消", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) { }
                        });
                        builder.create().show();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 獲取版本更新資訊的非同步任務
    public class getAPKUrl extends AsyncTask<String, Void, Message> {
        @Override protected void onPreExecute() { super.onPreExecute(); dialog.show(); }
        @Override protected Message doInBackground(String... params) {
            return HttpUtiles.getMessage(params[0]);
        }
        @Override protected void onPostExecute(Message result) {
            super.onPostExecute(result);
            dialog.dismiss();
        }
    }

    public class downLoadAPK extends AsyncTask<String, Void, Void> {
        @Override protected Void doInBackground(String... params) {
            String uri = HttpUtiles.downLoadApk(params[0]);
            // 透過檔案路徑安裝指定版本
            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;
        }
    }
}

HttpUtiles:取得版本資訊與下載 APK

一個方法以 JSON 格式取得版本資料,另一個方法負責把最新版本下載到 sdcard:

public class HttpUtiles {
    // 下載版本資訊,格式為 json
    public 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());
                JSONObject jsonObject = new JSONObject(json).getJSONObject("message");
                message.setVsersionCode(jsonObject.getInt("vsersionCode"));
                message.setApkUrl(jsonObject.getString("apkUrl"));
            }
        } catch (Exception e) {
            e.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);
                    fileOutputStream = new FileOutputStream(new File(file, name));
                    fileOutputStream.write(data, 0, data.length);
                    uri = file.getAbsolutePath() + "/" + name;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fileOutputStream != null) {
                try { fileOutputStream.close(); } catch (IOException e) { }
            }
        }
        return uri;
    }
}

PackUtiles:取得本地版本資訊

public class PackUtiles {
    private PackageInfo info;

    public PackUtiles(Context context) {
        initDate(context);
    }

    public void initDate(Context context) {
        PackageManager manager = context.getPackageManager();
        try {
            info = manager.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public int getVersion() { return info.versionCode; }
    public String getVersionName() { return info.versionName; }

    // 比較本地版本與伺服器版本號大小
    public boolean update(int oldVersion, int newVersion) {
        return newVersion > oldVersion;
    }
}

服務器端 Servlet

服務器端需事先匯入 JSON 的 jar 包。使用時別忘了把程式碼中的 HTTP 位址改成你自己電腦的 IP,並把待更新的 apk 放到 webroot 目錄下。

public class Install extends HttpServlet {
    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("https://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();
    }
}

至此,Android 客戶端與服務器端的程式碼都已完成。整套流程展示了如何透過 AsyncTask 異步請求伺服器、比對版本、下載 APK 並呼叫系統安裝器,完成應用的在線升級。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved