码迷,mamicode.com
首页 > 移动开发 > 详细

Android提示版本更新操作流程

时间:2014-05-09 01:37:21      阅读:449      评论:0      收藏:0      [点我收藏+]

标签:android   style   blog   class   code   java   

             

                                                        Android提示版本更新操作流程

 

 2014年5月8日:

 andorid的app应用中都会有版本更新的操作,今天空闲的时候就花了点心思弄了一下,主要技术方面用到了AsyncTask异步加载、http协议、json解析、获取版本号等。。。

 

下面就来介绍一下大概的流程吧,首先呢:

activity_main.xml:

 

    <Button 
        android:id="@+id/chek_newest_version"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dip"
        android:text="检测最新版本"/>


这里我就只用了一个按钮了!

 

接下来mainactivity代码:

启动了异步加载来处理的,如果旧版本小于新版本号,就开始执行下载操作,否则就不更新!

一步步看吧!

 

public class MainActivity extends Activity {

	Button m_btnCheckNewestVersion;
	long m_newVerCode; //最新版的版本号
	String m_newVerName; //最新版的版本名
	String m_appNameStr; //下载到本地要给这个APP命的名字
	
	Handler m_mainHandler;
	ProgressDialog m_progressDlg;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		//初始化相关变量
		initVariable();
		
		m_btnCheckNewestVersion.setOnClickListener(btnClickListener);
	}
	private void initVariable()
	{
		m_btnCheckNewestVersion = (Button)findViewById(R.id.chek_newest_version);
		m_mainHandler = new Handler();
		m_progressDlg =  new ProgressDialog(this);
		m_progressDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		 // 设置ProgressDialog 的进度条是否不明确 false 就是不设置为不明确     
		m_progressDlg.setIndeterminate(false);    
		m_appNameStr = "haha.apk";
	}
	
	OnClickListener btnClickListener = new View.OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			new checkNewestVersionAsyncTask().execute();
		}
	};
	
	class checkNewestVersionAsyncTask extends AsyncTask<Void, Void, Boolean>
	{
	
		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			if(postCheckNewestVersionCommand2Server())
			{
				int vercode = Common.getVerCode(getApplicationContext()); // 用到前面第一节写的方法  
		         if (m_newVerCode > vercode) {  
		             return true;
		         } else {  
		             return false;
		         }  
			}
			return false;
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			// TODO Auto-generated method stub
			if (result) {//如果有最新版本
				doNewVersionUpdate(); // 更新新版本  
			}else {
				notNewVersionDlgShow(); // 提示当前为最新版本  
			}
			super.onPostExecute(result);
		}
		
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}
	}
	
	/**
	 * 从服务器获取当前最新版本号,如果成功返回TURE,如果失败,返回FALSE
	 * @return
	 */
	private Boolean postCheckNewestVersionCommand2Server()
	{
		StringBuilder builder = new StringBuilder();
		JSONArray jsonArray = null;
		try {
			// 构造POST方法的{name:value} 参数对
			List<NameValuePair> vps = new ArrayList<NameValuePair>();
			// 将参数传入post方法中
			vps.add(new BasicNameValuePair("action", "checkNewestVersion"));
			builder = Common.post_to_server(vps);
			Log.e("msg", builder.toString());
			jsonArray = new JSONArray(builder.toString());
			if (jsonArray.length()>0) {
				if (jsonArray.getJSONObject(0).getInt("id") == 1) {
					m_newVerName = jsonArray.getJSONObject(0).getString("verName");
					m_newVerCode = jsonArray.getJSONObject(0).getLong("verCode");
					
					return true;
				}
			}
	
			return false;
		} catch (Exception e) {
			Log.e("msg",e.getMessage());
			m_newVerName="";
			m_newVerCode=-1;
			return false;
		}
	}
		
	/**
	 * 提示更新新版本
	 */
	private void doNewVersionUpdate() {
		int verCode = Common.getVerCode(getApplicationContext());  
	    String verName = Common.getVerName(getApplicationContext());  
	    
	    String str= "当前版本:"+verName+" Code:"+verCode+" ,发现新版本:"+m_newVerName+
	    		" Code:"+m_newVerCode+" ,是否更新?";  
	    Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新").setMessage(str)  
	            // 设置内容  
	            .setPositiveButton("更新",// 设置确定按钮  
	                    new DialogInterface.OnClickListener() {  
	                        @Override  
	                        public void onClick(DialogInterface dialog,  
	                                int which) { 
	                            m_progressDlg.setTitle("正在下载");  
	                            m_progressDlg.setMessage("请稍候...");  
	                            downFile(Common.UPDATESOFTADDRESS);  //开始下载
	                        }  
	                    })  
	            .setNegativeButton("暂不更新",  
	                    new DialogInterface.OnClickListener() {  
	                        public void onClick(DialogInterface dialog,  
	                                int whichButton) {  
	                            // 点击"取消"按钮之后退出程序  
	                            finish();  
	                        }  
	                    }).create();// 创建  
	    // 显示对话框  
	    dialog.show();  
	}
		/**
		 *  提示当前为最新版本  
		 */
		private void notNewVersionDlgShow()
		{
			int verCode = Common.getVerCode(this);  
		    String verName = Common.getVerName(this); 
		    String str="当前版本:"+verName+" Code:"+verCode+",/n已是最新版,无需更新!";
		    Dialog dialog = new AlertDialog.Builder(this).setTitle("软件更新")  
		            .setMessage(str)// 设置内容  
		            .setPositiveButton("确定",// 设置确定按钮  
		                    new DialogInterface.OnClickListener() {  
		                        @Override  
		                        public void onClick(DialogInterface dialog,  
		                                int which) {  
		                            finish();  
		                        }  
		                    }).create();// 创建  
		    // 显示对话框  
		    dialog.show();  
		}
		private void downFile(final String url)
		{
			m_progressDlg.show();  
		    new Thread() {  
		        public void run() {  
		            HttpClient client = new DefaultHttpClient();  
		            HttpGet get = new HttpGet(url);  
		            HttpResponse response;  
		            try {  
		                response = client.execute(get);  
		                HttpEntity entity = response.getEntity();  
		                long length = entity.getContentLength();  
		                
		                m_progressDlg.setMax((int)length);//设置进度条的最大值
		                
		                InputStream is = entity.getContent();  
		                FileOutputStream fileOutputStream = null;  
		                if (is != null) {  
		                    File file = new File(  
		                            Environment.getExternalStorageDirectory(),  
		                            m_appNameStr);  
		                    fileOutputStream = new FileOutputStream(file);  
		                    byte[] buf = new byte[1024];  
		                    int ch = -1;  
		                    int count = 0;  
		                    while ((ch = is.read(buf)) != -1) {  
		                        fileOutputStream.write(buf, 0, ch);  
		                        count += ch;  
		                        if (length > 0) {  
		                        	 m_progressDlg.setProgress(count);
		                        }  
		                    }  
		                }  
		                fileOutputStream.flush();  
		                if (fileOutputStream != null) {  
		                    fileOutputStream.close();  
		                }  
		                down();  //告诉HANDER已经下载完成了,可以安装了
		            } catch (ClientProtocolException e) {  
		                e.printStackTrace();  
		            } catch (IOException e) {  
		                e.printStackTrace();  
		            }  
		        }  
		    }.start();  
		}
		/**
		 * 告诉HANDER已经下载完成了,可以安装了
		 */
		private void down() {
	        m_mainHandler.post(new Runnable() {
	            public void run() {
	                m_progressDlg.cancel();
	                update();
	            }
	        });
	}
		/**
		 * 安装程序
		 */
	    void update() {
	        Intent intent = new Intent(Intent.ACTION_VIEW);
	        intent.setDataAndType(Uri.fromFile(new File(Environment
	                .getExternalStorageDirectory(), m_appNameStr)),
	                "application/vnd.android.package-archive");
	        startActivity(intent);
	    }


}


 

最后是Common.java类:

类似一个工具类,很多方法都写在这里面,下载完成后,开始执行安装的操作!

public class Common {
	public static final String SERVER_IP="http://192.168.1.105/";
	public static final String SERVER_ADDRESS=SERVER_IP+"try_downloadFile_progress_server/index.php";//软件更新包地址
	public static final String UPDATESOFTADDRESS=SERVER_IP+"try_downloadFile_progress_server/update_pakage/baidu.apk";//软件更新包地址

	/**
	 * 向服务器发送查询请求,返回查到的StringBuilder类型数据
	 * 
	 * @param ArrayList
	 *            <NameValuePair> vps POST进来的参值对
	 * @return StringBuilder builder 返回查到的结果
	 * @throws Exception
	 */
	public static StringBuilder post_to_server(List<NameValuePair> vps) {
		DefaultHttpClient httpclient = new DefaultHttpClient();
		try {
			HttpResponse response = null;
			// 创建httpost.访问本地服务器网址
			HttpPost httpost = new HttpPost(SERVER_ADDRESS);
			StringBuilder builder = new StringBuilder();

			httpost.setEntity(new UrlEncodedFormEntity(vps, HTTP.UTF_8));
			response = httpclient.execute(httpost); // 执行

			if (response.getEntity() != null) {
				// 如果服务器端JSON没写对,这句是会出异常,是执行不过去的
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(response.getEntity().getContent()));
				String s = reader.readLine();
				for (; s != null; s = reader.readLine()) {
					builder.append(s);
				}
			}
			return builder;

		} catch (Exception e) {
			// TODO: handle exception
			Log.e("msg",e.getMessage());
			return null;
		} finally {
			try {
				httpclient.getConnectionManager().shutdown();// 关闭连接
				// 这两种释放连接的方法都可以
			} catch (Exception e) {
				// TODO Auto-generated catch block
				Log.e("msg",e.getMessage());
			}
		}
	}
	
	/**
	 * 获取软件版本号
	 * @param context
	 * @return
	 */
	public static int getVerCode(Context context) {
        int verCode = -1;
        try {
        	//注意:"com.example.try_downloadfile_progress"对应AndroidManifest.xml里的package="……"部分
            verCode = context.getPackageManager().getPackageInfo(
                    "com.example.try_downloadfile_progress", 0).versionCode;
        } catch (NameNotFoundException e) {
        	Log.e("msg",e.getMessage());
        }
        return verCode;
    }
   /**
    * 获取版本名称
    * @param context
    * @return
    */
    public static String getVerName(Context context) {
        String verName = "";
        try {
            verName = context.getPackageManager().getPackageInfo(
                    "com.example.try_downloadfile_progress", 0).versionName;
        } catch (NameNotFoundException e) {
        	Log.e("msg",e.getMessage());
        }
        return verName;   
}
	
	
	
	
	
	

已经贴完毕!

 

 

 

Android提示版本更新操作流程,布布扣,bubuko.com

Android提示版本更新操作流程

标签:android   style   blog   class   code   java   

原文地址:http://blog.csdn.net/u014608640/article/details/25327615

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!