安卓下载更新

声明,本文参考网络文章,连接在此  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"/>

至此,打开网络,启动程序,即可测试


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值