Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android Studio實現APK的更新、下載、安裝

Android Studio實現APK的更新、下載、安裝

編輯:關於Android編程

先不講那麼多看效果圖:

\\

\\

下面來講解一些更新CODE,原理大家都知道,不廢話,直接上代碼。裡面有一些是我自己做的測試例子,所以大家可以直接刪掉就好了

第一個:activity_main.xml

\\
 1 
 2 
11 
12
View Code

第二個:MainActivity.java

\\
package com.example.fucm.wms_jianh;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import MyClass.HttpHelper;
import MyClass.SoftUpdate;

public class MainActivity extends Activity implements OnClickListener{
    Button btn1,btn2;
    ListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectDiskReads().detectDiskWrites().detectAll() // or
                // .detectAll()
                // for all
                // detectable
                // problems
                .penaltyLog().build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectLeakedSqlLiteObjects().detectLeakedClosableObjects()
                .penaltyLog().penaltyDeath().build());
        setContentView(R.layout.activity_main);
        btn1 = (Button) findViewById(R.id.btn_sq);
        btn2 = (Button) findViewById(R.id.button);
        btn1.setOnClickListener(this);
        listView = (ListView)findViewById(R.id.listView);
        btn2.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                SoftUpdate manager = new SoftUpdate(MainActivity.this);
                // 檢查軟件更新
                manager.checkUpdate();
            }
        });
    }
}
View Code

第三個:HttpHelper.java

\\
package MyClass;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;


public class HttpHelper {
    private static final int REQUEST_TIMEOUT = 15 * 1000;
    private static final int SO_TIMEOUT = 15 * 1000;

    public static String sendHttpRequest(String pUrl) {
        String result;
        result = doGet(pUrl);
        return result;
    }
    public static String doGet(String url) {
        String result = null;
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = httpClient.execute(httpGet);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {

            }
            result = EntityUtils.toString(response.getEntity(), "UTF-8");
        } catch (IOException e) {
            //Log.i("GET", "Bad Request!");
        }
        return result;
    }
    public static String GetJsonListValue(String str) {
        String strError="";
        try {
            JSONObject json1 = new JSONObject(str);
            JSONObject tmp = json1.getJSONObject("d");
            return tmp.getString("a");
        } catch (Exception e) {
            strError=e.toString();
        }
        return strError;

    }

    public static JSONArray GetJsonValue(String str) {

        try {
            JSONArray json1 = new JSONArray(str);
            return json1;
        } catch (Exception e) {
            //strError=e.toString();
        }
        return null;
    }
}
View Code

第四個:SoftUpdate.java

\\
package MyClass;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.fucm.wms_jianh.R;

import org.json.JSONArray;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by fucm on 2016-07-06.
 */
public class SoftUpdate {

    /* 下載中 */
    private static final int DOWNLOAD = 1;
    /* 下載結束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 保存解析的XML信息 */
    private Long str_version;
    private String str_appname;
    private String str_downurl;
    /* 下載保存路徑 */
    private String mSavePath;
    /* 記錄進度條數量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新進度條 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;

    public SoftUpdate(Context context)
    {
        this.mContext = context;
    }

    private Handler mHandler = new Handler()
    {
       public void handleMessage(Message msg)
        {
            switch (msg.what)
            {
                // 正在下載
                case DOWNLOAD:
                    // 設置進度條位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安裝文件
                    installApk();
                    break;
                default:
                    break;
            }
        };
    };

    /**
     * 檢測軟件更新
     */
    public void checkUpdate()
    {
        if (isUpdate())
        {
            // 顯示提示對話框
            showNoticeDialog();
        } else
        {
            Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 檢查軟件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate(){
        // 獲取當前軟件版本
        int versionCode = getVersionCode(mContext);
        //通過服務器獲得版本號
        try {
            String str = HttpHelper.sendHttpRequest("http://127.0.0.1/Service1.svc/get_version");
            JSONArray json1 =HttpHelper.GetJsonValue(str);
            str_version=json1.getLong(0);
            str_appname=json1.getString(1);
            str_downurl=json1.getString(2);
            if (str_version > versionCode) {
                return true;
            }
        }
        catch (Exception e) {
            //strError=e.toString();
        }
        return false;
    }

    /**
     * 獲取軟件版本號
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context)
    {
        int versionCode = 0;
        try
        {
            // 獲取軟件版本號,對應AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo("com.example.fucm.wms_jianh", 0).versionCode;
        } catch (PackageManager.NameNotFoundException e)
        {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 顯示軟件更新對話框
     */
    private void showNoticeDialog()
    {
        // 構造對話框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_update_title);
        builder.setMessage(R.string.soft_update_info);
        // 更新
        builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                // 顯示下載對話框
                showDownloadDialog();
            }
        });
        // 稍後更新
        builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    /**
     * 顯示軟件下載對話框
     */
    private void showDownloadDialog()
    {
        // 構造軟件下載對話框
        AlertDialog.Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        // 給下載對話框增加進度條
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.soft_update, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                // 設置取消狀態
                cancelUpdate = true;
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.show();
        // 現在文件
        downloadApk();
    }

    /**
     * 下載apk文件
     */
    private void downloadApk()
    {
        // 啟動新線程下載軟件
        new downloadApkThread().start();
    }

    /**
     * 下載文件線程
     *
     * @author coolszy
     *@date 2012-4-26
     *@blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread
    {
        @Override
        public void run()
        {
            try
            {
                // 判斷SD卡是否存在,並且是否具有讀寫權限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
                {
                    // 獲得存儲卡的路徑
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url= new URL(str_downurl);
                    // 創建連接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 獲取文件大小
                    int length = conn.getContentLength();
                    // 創建輸入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判斷文件目錄是否存在
                    if (!file.exists())
                    {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, str_appname);
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 緩存
                    byte buf[] = new byte[1024];
                    // 寫入到文件中
                    do
                    {
                        int numread = is.read(buf);
                        count += numread;
                        // 計算進度條位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新進度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0)
                        {
                            // 下載完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 寫入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 點擊取消就停止下載.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e)
            {
                e.printStackTrace();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
            // 取消下載對話框顯示
            mDownloadDialog.dismiss();
        }
    };

    /**
     * 安裝APK文件
     */
    private void installApk()
    {
        File apkfile = new File(mSavePath, str_appname);
        if (!apkfile.exists())
        {
            return;
        }
        // 通過Intent安裝APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

}
View Code

第五個:soft_update.xml

\\



    
View Code

第六個:AndroidManifest.xml(創建的時候自帶)

\\


    
    
    
    
        ".MainActivity">
            
                "android.intent.action.MAIN" />

                
            
        
        ".RwdMxActivity">
         
    

View Code

第七個:strings.xml(創建的時候自帶)

\\

    WMS_JIANH
    任務索取
    已經是最新版本
    軟件更新
    檢測到新版本,立即更新嗎
    更新
    稍後更新
    正在更新
    取消
View Code

第八個:看看工程結構

\

提供源碼下載:https://yunpan.cn/cBFKmGJKqiLct 訪問密碼 6e01

  1. 上一頁:
  2. 下一頁: