Androidアプリケーション自身の検出バージョンとダウンロード


構想:1サーバーの固定ディレクトリに固定したバージョンファイルを保存する;
           2.要求サーバ側のバージョンファイルを適用し、最新バージョンがあるかどうかを判断する.
     3.ダウンロード接続を作成し、最新apkをダウンロードします.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.DownloadManager;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.util.Xml;


/**
 * Created by shijian on 15-8-13.
 *       
 */
public class CheckVersionUtil {

    public void checkVersion(Context context) {

        this.context = context;
        threadPool.execute(checkVersion);
    }

    /**
     *       
     * @author shijian
     */
    Runnable checkVersion = new Runnable() {

        @Override
        public void run() {

            try {
                //             
                PackageInfo info = context.getPackageManager().getPackageInfo("cn.com.shijian.test", 0);
                float localVersion = Float.valueOf(info.versionName);
                float serverVersion = 0;

                //            
                String versionPath = CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkversionUrl);

                URL url = new URL(versionPath);

                HttpURLConnection conn= (HttpURLConnection)url.openConnection();

                //  XML     
                InputStream input = conn.getInputStream();
                //  XML  
                XmlPullParser parser = Xml.newPullParser();
                try {
                    parser.setInput(input, "utf-8");
                    int eventType = parser.getEventType();

                    while(eventType != XmlPullParser.END_DOCUMENT) {

                        switch (eventType) {

                            case XmlPullParser.START_TAG:

                                //  
                                if ("version".equals(parser.getName())) {

                                    serverVersion = Float.valueOf(parser.nextText());
                                }
                                //      
                                if("ismustupdate".equals(parser.getName())){
                                    ismustupdate = parser.nextText();
                                }
                                if ("description".equals(parser.getName())) {
                                    //  
                                    description = parser.nextText().replace("\
", "
");                                 }                                 break;                         }                         eventType = parser.next();                     }                     //                     if (serverVersion > localVersion) {                         boolean post = handler.post(new Runnable() {                             @Override                             public void run() {                                 Builder builder = new Builder(context);                                 builder.setTitle(" ");                                 builder.setMessage(description);                                 builder.setPositiveButton(" ", new DialogInterface.OnClickListener() {                                     @Override                                     public void onClick(DialogInterface dialog, int which) {                                         downloadApk();                                     }                                 });                                 if ("1".equals(ismustupdate)) {                                     builder.setNegativeButton(" ", new DialogInterface.OnClickListener() {                                         @Override                                         public void onClick(DialogInterface dialog, int which) {                                             dialog.dismiss();                                         }                                     });                                 }                                 AlertDialog dialog = builder.create();                                 dialog.show();                             }                         });                         //                     } else if (serverVersion <= localVersion) {                         if (context.getClass().equals(HomeActivity.class)) {                             return;                         }                         handler.post( new Runnable() {                             public void run() {                                 AlertDialog.Builder builder = new Builder(context);                                 builder.setTitle(" ");                                 builder.setMessage(" ");                                 AlertDialog dialog = builder.create();                                 dialog.show();                             }                         });                     }                 } catch (XmlPullParserException e) {                     e.printStackTrace();                 }             } catch (NameNotFoundException e) {                 e.printStackTrace();             } catch (MalformedURLException e) {                 e.printStackTrace();             } catch (IOException e) {                 e.printStackTrace();             } finally {                 threadPool.shutdown();             }         }     };     /**      *      *  apk      * @author shijian      * @since 2015-8-13      */     public void downloadApk() {         // DownloadManager         final DownloadManager downloadMgr = (DownloadManager)  context.getSystemService(Context.DOWNLOAD_SERVICE);         // URI         Uri apkLocation = Uri.parse(CommonUtil.prefixUrl + File.separator + context.getString(R.string.apkUrl));         Request  request = new Request(apkLocation);         //request.setAllowedNetworkTypes(Request.NETWORK_WIFI);         request.setTitle("e ");         //         File folder = Environment.getExternalStoragePublicDirectory("echewen");         if (folder.exists() && folder.isDirectory()){         } else {             folder.mkdirs();         }         // echewen.apk ,         File apk = new File(CheckVersionUtil.APK_UPDATE);         if (apk.exists()) {             apk.delete();         }         //         request.setDestinationInExternalPublicDir("echewen", "echewen.apk");         // downloadmanager ID         final long ref = downloadMgr.enqueue(request);         IntentFilter filter =  new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);         BroadcastReceiver receiver = new BroadcastReceiver() {             @Override             public void onReceive(Context context, Intent intent) {                 long mRef = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);                 if (mRef == ref) {                     Cursor c = downloadMgr.query(new DownloadManager.Query().setFilterById(mRef));                     c.moveToFirst();                     String downloadFile = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));                     Intent installIntent = new Intent(Intent.ACTION_VIEW);                     installIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);                     installIntent.setDataAndType(Uri.parse(downloadFile),                             "application/vnd.android.package-archive");// intent                     context.startActivity(installIntent);                 }             }         };         context.registerReceiver(receiver, filter);     }     //     ExecutorService threadPool = Executors.newCachedThreadPool();     Handler handler = new Handler();     //     String description;     //     Context context;     String ismustupdate = "0";//0: ;1:     public static final String APK_UPDATE = Environment.getExternalStorageDirectory().getPath() + "/echewen/echewen.apk";     public static final String STORAGE_IMAGE_PATH = Environment.getExternalStorageDirectory().getPath() + "/echewen/apk/"; }