安卓下載更新

聲明,本文參考網絡文章,連接在此  http://www.tuicool.com/articles/2qmEnm

本文只修改了下載的地址,下載一個小的apk,只有幾百KB,方便測試。同時增加了下載百分比的數字顯示


一般客戶端都需要通過網絡來更新,此處提供下載和安裝的demo

1.MainActivity的佈局xml如圖

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
</LinearLayout>

下載進度條的佈局xml如圖

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:orientation="vertical">

    <ProgressBar
        android:id="@+id/progress"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="fill_parent"
        android:layout_height="20dp" >
    </ProgressBar>
    
    <TextView android:id="@+id/showProgress"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="0%"
        android:layout_marginTop="20dp"/>

    <Button android:id="@+id/cancel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="取消下載"
        android:layout_gravity="center"
        android:layout_marginTop="20dp"/>
</LinearLayout>


2.定義MainActivity,彈出下載提示框,直接在java代碼中使用AlertDialog實現,整個Activity源碼如下

public class MainActivity extends Activity {
    private UpdateManager mUpdateManager;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
         
        mUpdateManager = new UpdateManager(this);
        mUpdateManager.checkUpdateInfo();
    }    
}

3.UpdateManager代碼如下

public class UpdateManager {
	private Context context;
	private Dialog tipsDialog,downloadDialog;
	private String urlStr="http://count.liqucn.com/d.php?id=11365&ArticleOS=android&content_url="
    		+ "http://www.liqucn.com/rj/11365.shtml&down_url=kpa.moc.ncuqil_0.4_lacarukas.tsitratib/naimouhz/daolpu/moc.ncuqil.elif//:ptth&is_cp=0&market_place_id=11";
	
	private static final String FILE_PATH = Environment.getExternalStorageDirectory() + "/" +"updatedemo" + "/";
	private static final String FILE_NAME = FILE_PATH + "updatedemo.apk"; 
	private ProgressBar bar;
	private boolean cancel=false;
	private final int DONE=0;
	private final int DOING=1;
	private int progress;
	private TextView showProgress;
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch(msg.what){
			case DONE: installApp();
				break;
			case DOING:
				bar.setProgress(progress);
				showProgress.setText(progress+"%");
				break;
			default: break;
			}
		};
	};
		
	public UpdateManager(Context context){
		this.context=context;
	}
	
	protected void checkUpdateInfo(){
		//顯示提示更新對話框
		Builder build=new Builder(context);
		build.setTitle("提示更新");
		build.setMessage("有新版本,請更新!!!");
		build.setPositiveButton("下載更新",new OnClickListener(){
			public void onClick(DialogInterface dialog, int which) {
				//開始下載
				tipsDialog.dismiss();
				Builder build2=new Builder(context);
				build2.setTitle("下載中...");
				View view=LayoutInflater.from(context).inflate(R.layout.progress,null);
				build2.setView(view);
				downloadDialog=build2.create();
				downloadDialog.show();
				
				Button button=(Button)view.findViewById(R.id.cancel);
				button.setOnClickListener(new android.view.View.OnClickListener(){
					public void onClick(View v) {
						downloadDialog.dismiss();
						cancel=true;
					}					
				});
				bar=(ProgressBar)view.findViewById(R.id.progress);
				showProgress=(TextView)view.findViewById(R.id.showProgress);
				//啓動線程,訪問網絡
				Thread thread=new Thread(new DownLoadRunnable());
				thread.start();
			}			
		});
		build.setNegativeButton("以後再說",new OnClickListener(){
			public void onClick(DialogInterface dialog, int which) {
				// 取消下載
				tipsDialog.dismiss();
			}
		});
		tipsDialog=build.create();
		tipsDialog.show();
	}
	
	class DownLoadRunnable implements Runnable{
		public void run() {
			URL url;
			HttpURLConnection connect=null;
			InputStream in=null;
			FileOutputStream out = null;
			try {
				url = new URL(urlStr);
				connect=(HttpURLConnection) url.openConnection();
				connect.connect();
				long apkLength=connect.getContentLength();
				in=connect.getInputStream();
				
				File filePath=new File(FILE_PATH);
				if(!filePath.exists())
					filePath.mkdir();
				out=new FileOutputStream(FILE_NAME);
				
				long readLength=0;
				byte[] array=new byte[1024];
				int len=0;
				while((len=in.read(array))!=-1){
					if(cancel)
						break;
					out.write(array,0,len);
					readLength+=len;
					progress=(int)(((float)readLength/apkLength)*100);
					handler.sendEmptyMessage(DOING);
					if(readLength>=apkLength){
						out.flush();
						downloadDialog.dismiss();
						//安裝APK
						handler.sendEmptyMessage(DONE);
						break;
					}					
				}
				 
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					if(out!=null)
					   out.close();
					if(in!=null)
						in.close();
					if(connect!=null)
						connect.disconnect();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
		}
	}

	//調用系統去安裝apk
	private void installApp(){
		File appFile=new File(FILE_NAME);
		if(!appFile.exists())
			return;
		Intent intent=new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse("file://" + appFile.toString()), "application/vnd.android.package-archive");
		context.startActivity(intent);
	}
}

4.在Menifest.xml中加入權限,包括網絡訪問,文件讀寫

<uses-permission android:name="android.permission.INTERNET"/>
 <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

至此,打開網絡,啓動程序,即可測試


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章