Androidはバージョンをダウンロードして更新します

15674 ワード

プロセス:1.サーバーの向こうにプロファイルを引いて、プロファイルを解析してアプリケーションのアドレス、バージョン番号、サイズ、md 5と構成の更新方法(オプションの更新と強制更新)を取得します.
   2.ブレークポイントリレー方式でapkを引きます.
以下をコードとします.

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;


import com.longjiang.youzhong.R;
import com.uzone.util.Md5Check;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;


//         ->             apk     、        ->     :(1)     ,    ;(2)    :a,     ;b,     .    1.  apk      ,        
public  class VersionActivity extends Activity{

	//            url
	private static String requestUrl="http://192.168.1.46/updateversion/updateversion.php";
	private static String version ;
	private static String apkDownUrl;
	private static int updateType;//1,        ;2,      
	private static ProgressDialog checkDialog;
	private static Activity context;	
	private static  MyHandler mHandler; 
	private static  int retry; 
	private static String path; 
	private static String packageName;
	private static String md5;	
	private static long  fileTotalSize;	
	private static ProgressDialog pbar;
	private String tag="VersionActivity";
	private int TryDownTotal=5;//           
	private static String fileName="longjiang.apk"; 
	private interface  DialogHandler{
		  void fun();
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.yzupdate);
		pbar =new ProgressDialog(this);
		
		context=this;
		mHandler=new MyHandler();
		checkDialog = ProgressDialog.show(this, null, getString(R.string.version_check_msg), true);
		checkDialog.setCancelable(false);
		checkVersion();
	
	
	}
	
	
	
	public static void checkVersion()
	{
		
		//            
		new Thread(new Runnable() {
			@Override
			public void run() {
        // HttpGet      
        HttpGet httpRequest = new HttpGet(requestUrl);  
        try {  
            //   HttpClient    
            HttpClient httpclient = new DefaultHttpClient();  
            //   HttpClient,  HttpResponse  
            HttpResponse httpResponse = httpclient.execute(httpRequest);  
            //       
            if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {  
				String jsonResult = EntityUtils.toString(
						httpResponse.getEntity(), HTTP.UTF_8);
				
				JSONObject paramsjson = new JSONObject(jsonResult);
				version=paramsjson.optString("version");
				apkDownUrl=paramsjson.optString("apkDownUrl");
				updateType=paramsjson.optInt("updateType");		
				md5=paramsjson.optString("md5");	
				fileTotalSize=Long.valueOf(paramsjson.optString("size"));	
				
				Message msg = Message.obtain(mHandler);
				msg.what = 0;
				//msg.obj = resultObj;
				mHandler.sendMessage(msg);
            } else {  
               //       
            	
				Message msg = Message.obtain(mHandler);
				msg.what = 1;
				//msg.obj = resultObj;
				mHandler.sendMessage(msg);
            	
            }  
        } catch (ClientProtocolException e) {  
          
        } catch (IOException e) {  
           
        } catch (Exception e) {  
       
        }  
			}
		
			}).start();

	}
	
	
	
	
	
	 //       ,   button        button     
	private static void showDialog(String title,String content,String rightButton,String leftButton,final DialogHandler Rhandler,final DialogHandler Lhandler)
	{
		
		
		if(rightButton==null)
		{
			new AlertDialog.Builder(context)
					.setTitle(title)
					.setMessage(content)
					.setCancelable(false)
					.setPositiveButton(leftButton,
							new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int id) {
										dialog.dismiss();
												
										if(Lhandler!=null)
											Lhandler.fun();
												
									}
								}).show();
			
		}
		
		else if(leftButton!=null&&rightButton!=null)
		{

			new AlertDialog.Builder(context)
					.setTitle(title)
					.setMessage(content)
					.setCancelable(false)
					.setPositiveButton(leftButton,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int id) {
									dialog.dismiss();
									Lhandler.fun();
								}
							})
					.setNegativeButton(rightButton,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									dialog.dismiss();
									
									if(Rhandler!=null)
										Rhandler.fun();
								}
							}).show();
			
		}
	}

	  
	  private  class MyHandler extends Handler {

			@Override
			public void handleMessage(final Message msg) {


				switch (msg.what) {
				case 0:
					//  apk    
					checkDialog.dismiss();
					PackageInfo info;  
					try {  
					    info = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);  
					    //            
					    //String versionName = info.versionName;  
					    //           
					    int versionCode = info.versionCode;  
					    packageName=info.applicationInfo.packageName;
					    //    
					    if(versionCode<Integer.valueOf(version))
					    {
					    	//    
					    	
					    	//      
					    	if(updateType==1)//test 0
					    	{
								 showDialog(context.getString(R.string.updatetitle),"        "+versionCode+"      "+version,"    ","     ",new DialogHandler(){
						    		 
						    		 public void fun(){ 	
						    			 
						    			 predownloadapk();
						    			 
										}	    		 
						    	 }
								 , new DialogHandler(){
						    		 
						    		 public void fun(){ startGame(); }	    		 
						    		 
						    	 });
					    		
					    	}
					    	//    
					    	else if(updateType==1)
					    	{
								 showDialog(context.getString(R.string.updatetitle),"            :"+version,null,"  ",null, new DialogHandler(){
						    		 
						    		 public void fun(){ 
 
						    			 predownloadapk();

						    			 }	    		 
						    	 });
					    	}
					    }
					    //    apk,      
					    else
					    {
					    	startGame();
					    }
					    
					} catch (NameNotFoundException e) {  
					    e.printStackTrace();  
					}  
					
					break;
				case 1:
					//         
			    	 showDialog(context.getString(R.string.networkerror),context.getString(R.string.comfirmexist),null,context.getString(R.string.comfirmexist),null, new DialogHandler(){
			    		 
			    		 public void fun(){ context.finish(); }	    		 
			    		 
			    	 });
					break;
					
				case 2:
					
			    	 
					break;	
					
				case 3:
					//      
		        	if(md5.equals(Md5Check.md5sum(new File(path+"/"+fileName))))
		        	{
		        		ReplaceLaunchApk(path+"/"+fileName);
		        	}
		        	else if(retry<TryDownTotal)
		        	{
		        		retry++;
		        		downloadapk();
		        		
		        	}
		        	else
		        	{
		        		
				    	 showDialog(context.getString(R.string.networkerror),context.getString(R.string.comfirmexist),null,context.getString(R.string.comfirmexist),null, new DialogHandler(){
				    		 
				    		 public void fun(){ context.finish(); }	    		 
				    		 
				    	 });
		        		
		        	}
					break;
					
				case 4:
					//t    
			    	 showDialog("  ","        ",null,context.getString(R.string.comfirmexist),null, new DialogHandler(){
			    		 
			    		 public void fun(){ context.finish(); }	    		 
			    		 
			    	 });
					break;
					
				case 5:
					//t     
			    	 showDialog("  ","          ,         ",null,context.getString(R.string.comfirmexist),null, new DialogHandler(){
			    		 
			    		 public void fun(){ context.finish(); }	    		 
			    		 
			    	 });
					break;
					
					
				default:
					break;
				}
			}
		}

	  
  private void startGame()
	  {
			Intent intent = new Intent(context, LongjiangActivity.class);
			startActivity(intent);  
			context.finish();
		  
	  }
  
  
// url   apk
  private void predownloadapk()
  {
	  retry=0;

	//      
	  downloadapk();  
  }
  
  private void downloadapk()
  {
	  //
	  pbar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	  pbar.setTitle("            :"+version);
	  pbar.setMessage("     ,   ...");
	  pbar.setCancelable(false);
	  pbar.setMax(100);
	  pbar.setProgress(0);
	  pbar.show();

	  new DownloadFilesTask().execute(apkDownUrl);
	  
  }
  
  
  //      
  class DownloadFilesTask extends AsyncTask<String,Integer,Long> {

      private URL  url; //     
      private long beginPosition; //     




      @Override
      protected Long doInBackground(String... params) {
    	  
    	  
          InputStream inputStream = null;
          HttpURLConnection httpURLConnection =null;
          RandomAccessFile output = null;
          try {
              //       h
        	  
        	  
        	  //        
        	  boolean hasSD = Environment.getExternalStorageState().equals( android.os.Environment.MEDIA_MOUNTED);          //         
        	  if(!hasSD)
        	  {
        		  
      			Message msg = Message.obtain(mHandler);
      			msg.what = 4;
      			mHandler.sendMessage(msg);
        		return (long) 0;
        	  }
        	  long availablesize=getUsableStorage();
        	  if(availablesize<100)
        	  {
        		  
      			Message msg = Message.obtain(mHandler);
      			msg.what = 5;
      			mHandler.sendMessage(msg); 
        		return (long) 0;
        	  }
        	  
        	  String sddir=getSDCardPath() ;
        	  
        	  path=sddir+"/"+packageName;
        	  File destDir = new File(sddir+"/"+packageName);
        	  if (!destDir.exists()) {
        	   destDir.mkdirs();
        	  }
        	  
              File outFile = new File(sddir+"/"+packageName+"/"+fileName);  
              if (!outFile.exists()) {  
                    try {  
                        //              
                    	outFile.createNewFile();  
                  } catch (Exception e) {  
                  }  
              } 
        	  
           //            RandomAccessFile,r:  w:  d:  
         output = new RandomAccessFile(outFile, "rw");
          //       
     
         long lenth=outFile.length();    

         
         if(fileTotalSize==lenth)  
         {
        	 
        	if(md5.equals(Md5Check.md5sum(outFile)) )
        	{
        		
        		//      
        		publishProgress(100);
    			Message msg = Message.obtain(mHandler);
    			msg.what = 3;
    			mHandler.sendMessage(msg);
        		return lenth;
        	}	
        	else
        	{
        		beginPosition=0;
        		
        	}

         }
         else
         {
        	 beginPosition=lenth;
         }

              //             
         url=new URL(params[0]);
         httpURLConnection = (HttpURLConnection) url.openConnection();
         httpURLConnection = (HttpURLConnection)url.openConnection(); 
         httpURLConnection.setAllowUserInteraction(true); 
         httpURLConnection.setRequestMethod("GET"); 
         httpURLConnection.setReadTimeout(4000); 
        // httpURLConnection.setRequestProperty("User-Agent","NetFox"); 
         httpURLConnection.setRequestProperty("Range", "bytes=" + beginPosition + "-"); 
         inputStream = httpURLConnection.getInputStream(); 
        	  
         output.seek(beginPosition);	  
         byte[] buf = new byte[1024*100];
         int readsize=0;
         //       
         while ((readsize=inputStream.read(buf)) != -1) {
        	 
        	 
        	 
        	 output.write(buf, 0, readsize);
        	 beginPosition+=readsize;
             publishProgress((int)(beginPosition*100.0f/fileTotalSize)); 

         }
         

          } catch (Exception ex) {
              ex.printStackTrace();
          }
          finally { 

              if(inputStream!=null) { 
                  try { 
                	  inputStream.close(); 

                    	  
                     if(output!=null) { 
                        output.close(); 
                      } 
                      if(httpURLConnection!=null) { 
                    	  httpURLConnection.disconnect(); 
                      } 
                    } 
                  catch (IOException e) { 
                      e.printStackTrace(); 
                  } 
              } 
          }
          return beginPosition;
      }
      
      /** 
       *       , publishProgress                    
       */ 
      @Override 
      protected void onProgressUpdate(Integer... values) { 
          super.onProgressUpdate(values); 
          
    	  pbar.setProgress(values[0]);
    	  if(values[0]==100)
    	  {
			Message msg = Message.obtain(mHandler);
			msg.what = 3;
			mHandler.sendMessage(msg);  
    	  }
      }
      //      
      @Override 
      protected void onPostExecute(Long size)
      {

      }
  }
  

  
  /**
   *     SD   
   * 
   * @return
   */
  public static String getSDCardPath() {

      return Environment.getExternalStorageDirectory().getPath();
  } 
  
  
  
 /* 
  *   SD       --# 
  */  
  private static long getUsableStorage(){  
    String sDcString = android.os.Environment.getExternalStorageState();  
        
     if (sDcString.equals(android.os.Environment.MEDIA_MOUNTED)) {  
         File pathFile = android.os.Environment  
                 .getExternalStorageDirectory();  

         android.os.StatFs statfs = new android.os.StatFs(pathFile.getPath());  
           
     //          Block     
         long nAvailaBlock = statfs.getAvailableBlocks();  

         long nBlocSize = statfs.getBlockSize();  

     //    SDCard     MB  
         return nAvailaBlock * nBlocSize /1024 /1024;  
     }  
     else{  
         return -1;  
     }  
       

 }   
  
  
  
  //      apk
  private void ReplaceLaunchApk(String apkpath) {
      // TODO Auto-generated method stub
	  File file=new File(apkpath);
	  if(file.exists())
	  {
		  Log.e(tag, file.getName());
		  Intent intent = new Intent();
		  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		  intent.setAction(android.content.Intent.ACTION_VIEW);
		  intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
		  startActivity(intent);
		  context.finish();
	  }
	  else
	  {
		  Log.e(tag, "File not exsit:"+apkpath);
	  }
}	
}

参照先:http://www.eoeandroid.com/thread-1081-1-1.htmlその他