安卓版本更新demo

////////////////////2016/04/25//////////////////////

///////////////////by XBW///////////////////////////

//////////////////环境 eclipse api22///////////

做点贡献,发几个小demo,每次启动某个app都会遇到app升级,这是怎么实现的呢,先上图吧,

有图有真相,

这截图真大,没睡了,

结构。

Config.java

package com.example.update;

public class Config {
public static String mysql_url_update="http://127.0.0.1/androidapp/appupdate/update.txt";//服务器端更新url;
}

FileUtil.java

package com.example.update;
import java.io.File;
import java.io.IOException;
import android.os.Environment;

public class FileUtil {
	
	public static File updateDir = null;
	public static File updateFile = null;
	public static final String Application = "konkaUpdateApplication";
	
	public static boolean isCreateFileSucess;
	public static void createFile(String app_name) {
		
		if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState())) {
			isCreateFileSucess = true;
			
			updateDir = new File(Environment.getExternalStorageDirectory()+ "/" +Application +"/");
			updateFile = new File(updateDir + "/" + app_name + ".apk");

			if (!updateDir.exists()) {
				updateDir.mkdirs();
			}
			if (!updateFile.exists()) {
				try {
					updateFile.createNewFile();
				} catch (IOException e) {
					isCreateFileSucess = false;
					e.printStackTrace();
				}
			}

		}else{
			isCreateFileSucess = false;
		}
	}
}

GetVersion.java

package com.example.update;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;

public class GetVersion {

	// 获取当前版本的版本号
		public String getVersion(Context context) {
			try {
				PackageManager packageManager = context.getPackageManager();
				PackageInfo packageInfo = packageManager.getPackageInfo(
						context.getPackageName(), 0);
				return packageInfo.versionName;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
				return "版本号未知";
			}
		}
}

IsNeedUpdate.java

package com.example.update;

import android.content.Context;

public class IsNeedUpdate {

	private UpdateInfo info;
	public IsNeedUpdate(Context context){
		UpdateInfoService updateInfoService = new UpdateInfoService(
				context);
		try {
			info = updateInfoService.getUpDateInfo();
		} catch (Exception e) {
			// TODO 自动生成�? catch �?
			e.printStackTrace();
		}
	}
	public boolean isNeedUpdate(Context context) {
		 GetVersion version=new GetVersion();
		 //版本更新检测使用浮点型存在小版本问题,浮点型不能识别v 1.2.1这种小版本
		 //double webVersion=Double.parseDouble(info.getVersion());
		// double localVersion=Double.parseDouble(version.getVersion(context));
		 //采用比较字典序大小检测版本更新
		if (info.getVersion().compareTo(version.getVersion(context))>0) {
			return true;
		} else {
			return false;
		}
	}
	public String getDescribe(){
		
		return info.getDescription();
	}
	public String getUrl(){
		
		return info.getUrl();
	}
}

ShowUpdateDialog.java

package com.example.update;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ShowUpdateDialog{
	private UpdateInfo info;
	//更新窗口
	public Dialog showUpdateDialog(final Context context,String msg,final String url) {
		LayoutInflater layoutInflater =LayoutInflater.from(context);
		RelativeLayout layout = (RelativeLayout)layoutInflater.inflate(R.layout.dialog, null );
		final Dialog dialog = new AlertDialog.Builder(context).create();
	    dialog.show();
	    dialog.getWindow().setContentView(layout);
	    TextView tex=(TextView)layout.findViewById(R.id.dialog_text);
	    TextView tex1=(TextView)layout.findViewById(R.id.textView_title);
	    tex.setMovementMethod(ScrollingMovementMethod.getInstance()); 
	    tex.setText(msg);
	    tex1.setText("更新提示");
         //确定按钮
         Button btnOK = (Button) layout.findViewById(R.id.dialog_ok);
         btnOK.setOnClickListener(new OnClickListener() {         
           @Override 
           public void onClick(View v) { 
        	   if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
        		   		//services.service();
        		   Intent intent = new Intent(context,UpdateServices.class);
        		   intent.putExtra("Key_App_Name",context.getString(R.string.app_name));
        		   intent.putExtra("Key_Down_Url",url);		
        		   context.startService(intent);
				} else {
					Toast.makeText(context, "SD卡不可用,请插入SD卡",
							Toast.LENGTH_SHORT).show();
				}
        	   dialog.dismiss();    
           }
         });	 
         //关闭按钮
         ImageButton btnClose = (ImageButton) layout.findViewById(R.id.dialog_close);
         btnClose.setOnClickListener(new OnClickListener() {	          
           @Override
           public void onClick(View v) {
              dialog.dismiss();          
           }
         });
         return dialog;
     }
	//不更新窗口
	public Dialog showDialog(final Context context) {
		LayoutInflater layoutInflater =LayoutInflater.from(context);
		RelativeLayout layout = (RelativeLayout)layoutInflater.inflate(R.layout.dialog, null );
		final Dialog dialog = new AlertDialog.Builder(context).create();
	    dialog.show();
	    dialog.getWindow().setContentView(layout);
	    TextView tex=(TextView)layout.findViewById(R.id.dialog_text);
	    TextView tex1=(TextView)layout.findViewById(R.id.textView_title);
	    GetVersion version=new GetVersion();
	    tex.setText("您使用的是最新版:"+version.getVersion(context)+"版本");
	    tex1.setText("更新提示");
	    Button btnOK = (Button) layout.findViewById(R.id.dialog_ok);
	    btnOK.setVisibility(View.INVISIBLE);
	  //关闭按钮
         ImageButton btnClose = (ImageButton) layout.findViewById(R.id.dialog_close);
         btnClose.setOnClickListener(new OnClickListener() {	          
           @Override
           public void onClick(View v) {
              dialog.dismiss();          
           }
         });
         return dialog;
	}

}

UpdateInfo.java

package com.example.update;

public class UpdateInfo
{
        private String version;
        private String description;
        private String url;
        public String getVersion()
        {
                return version;
        }
        public void setVersion(String version)
        {
                this.version = version;
        }
        public String getDescription()
        {
                return description;
        }
        public void setDescription(String description)
        {
                this.description = description;
        }
        public String getUrl()
        {
                return url;
        }
        public void setUrl(String url)
        {
                this.url = url;
        }
}

UpdateInfoService.java

package com.example.update;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.content.Context;

public class UpdateInfoService {
	public UpdateInfoService(Context context) {
	}

	public UpdateInfo getUpDateInfo() throws Exception {
		String path = Config.mysql_url_update;
		StringBuffer sb = new StringBuffer();
		String line = null;
		BufferedReader reader = null;
		UpdateInfo updateInfo = new UpdateInfo();
		try {
			// 创建�?个url对象
			URL url = new URL(path);
			// 通過url对象,创建一个HttpURLConnection对象(连接)
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();
			// 通过HttpURLConnection对象,得到InputStream
			reader = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			// 使用io流读取文�?
			while ((line = reader.readLine()) != null) {
				sb.append(line);
				
				
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	
		String info = sb.toString();
		updateInfo.setVersion(info.split("&")[1]);
		updateInfo.setDescription(info.split("&")[2]);
		updateInfo.setUrl(info.split("&")[3]);
		return updateInfo;
	}

}

UpdateServices.java

package com.example.update;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.RemoteViews;
import android.widget.Toast;

public class UpdateServices extends Service{
	public static final String Install_Apk = "Install_Apk";
	private static final int down_step_custom = 3;
	private static final int TIMEOUT = 10 * 1000;
	private static String down_url;
	private static final int DOWN_OK = 1;
	private static final int DOWN_ERROR = 0;
	private String app_name;
	private NotificationManager notificationManager;
	private Notification notification;
	private Intent updateIntent;
	private PendingIntent pendingIntent;
	private RemoteViews contentView;
	public final static String ACTION_BUTTON = "com.notifications.intent.action.ButtonClick";
	public final static String INTENT_BUTTONID_TAG = "ButtonId";
	public final static int BUTTON_PREV_ID = 1;
	public final static int BUTTON_PALY_ID = 2;
	public final static int BUTTON_NEXT_ID = 3;
	public ButtonBroadcastReceiver bReceiver;
	public boolean jud=false;
	@Override
	public IBinder onBind(Intent intent) {
		// TODO 自动生成的方法存�?
		return null;
	}
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		
		app_name = intent.getStringExtra("Key_App_Name");
		down_url = intent.getStringExtra("Key_Down_Url");
		FileUtil.createFile(app_name);
		if(FileUtil.isCreateFileSucess == true){	
			jud=true;
			createNotification();
			createThread();
		}else{
			Toast.makeText(this, "无内存卡", Toast.LENGTH_SHORT).show();
			stopSelf();
			
		}
		return super.onStartCommand(intent, flags, startId);
	} 
	private final Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case DOWN_OK:
				Uri uri = Uri.fromFile(FileUtil.updateFile);
				notification.flags = Notification.FLAG_AUTO_CANCEL; 				 
				notification.setLatestEventInfo(UpdateServices.this,app_name, "下载成功", pendingIntent);		
				notificationManager.notify(R.layout.notification_item, notification);	
				installApk();	
				stopService(updateIntent);
				stopSelf();
				break;
			case DOWN_ERROR:
				notification.flags = Notification.FLAG_AUTO_CANCEL; 
				notification.setLatestEventInfo(UpdateServices.this,app_name, "下载失败", null);
				onDestroy();
				stopSelf();
				break;
			default:
				stopService(updateIntent);
				stopSelf();
				break;
			}
		}
	};
	private void installApk() {
		// TODO Auto-generated method stub
		Uri uri = Uri.fromFile(FileUtil.updateFile);
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
		intent.setDataAndType(uri,"application/vnd.android.package-archive");			        
        UpdateServices.this.startActivity(intent);	       
	}
	public void createThread() {
		new DownLoadThread().start();
	}
	private class DownLoadThread extends Thread{
		@Override
		public void run() {
			// TODO Auto-generated method stub
			Message message = new Message();
			try {								
				long downloadSize = downloadUpdateFile(down_url,FileUtil.updateFile.toString());
				if (downloadSize > 0) {					
					// down success										
					message.what = DOWN_OK;
					handler.sendMessage(message);																		
				}
			} catch (Exception e) {
				e.printStackTrace();
				message.what = DOWN_ERROR;
				handler.sendMessage(message);
			}						
		}		
	}
	
	@SuppressWarnings("deprecation")
	public void createNotification() {
		notification = new Notification(
				R.drawable.ic_launcher,
				app_name + "正在下载",
				System.currentTimeMillis());
		notification.flags = Notification.FLAG_ONGOING_EVENT; 
		//notification.flags = Notification.FLAG_AUTO_CANCEL;	 
		contentView = new RemoteViews(getPackageName(),R.layout.notification_item);
		initButtonReceiver();//启动广播监听    忘记启动会�?�成 按钮无响�?
		contentView.setTextViewText(R.id.notificationTitle, app_name + "正在下载");
		contentView.setTextViewText(R.id.notificationPercent, "0%");
		contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
		// 点击的事件处�?
		Intent buttonIntent = new Intent(ACTION_BUTTON);
		//按钮1
		buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
		// 这里加了广播,所及INTENT的必须用getBroadcast方法
		PendingIntent intent_prev = PendingIntent.getBroadcast(this, 1,
				buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		contentView.setOnClickPendingIntent(R.id.btn_close, intent_prev);
		//按钮2
		buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
		PendingIntent intent_paly = PendingIntent.getBroadcast(this, 2,
				buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		contentView.setOnClickPendingIntent(R.id.relativelayout_btn, intent_paly);		
		notification.contentView = contentView;
		updateIntent = new Intent(this, MainActivity.class);
		updateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		//updateIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		pendingIntent = PendingIntent.getActivity(this, 0, updateIntent, 0);
		notification.contentIntent = pendingIntent;
		
		notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
		notificationManager.notify(R.layout.notification_item, notification);
	}
	/** 带按钮的通知栏点击广播接�? */
	public void initButtonReceiver() {
		bReceiver = new ButtonBroadcastReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ACTION_BUTTON);
		getApplication().registerReceiver(bReceiver, intentFilter);//加上getApplication()不易丢失
	}

	/**
	 * 广播监听按钮点击时间
	 */
	public class ButtonBroadcastReceiver extends BroadcastReceiver {
	
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(ACTION_BUTTON)) {
				// 通过传�?�过来的ID判断按钮点击属�?�或者�?�过getResultCode()获得相应点击事件
				int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);
				switch (buttonId) {
				case BUTTON_PREV_ID:
					notificationManager.cancel(R.layout.notification_item);//删除�?个特定的通知ID对应的�?�知
					jud=false;
					stopService(updateIntent);
					stopSelf();
					//onDestroy();
					//getApplicationContext().unregisterReceiver(this);
					break;
				case BUTTON_PALY_ID:
					Toast.makeText(UpdateServices.this, "正在更新…",
							Toast.LENGTH_LONG).show();
					break;
				default:
					break;
				}
			}
		}
	}
	public PendingIntent getDefalutIntent(int flags){
		PendingIntent pendingIntent= PendingIntent.getActivity(this, 1, new Intent(), flags);
		return pendingIntent;
	}
	public long downloadUpdateFile(String down_url, String file)throws Exception {
		
		int down_step = down_step_custom;
		int totalSize;
		int downloadCount = 0;
		int updateCount = 0;
		InputStream inputStream;
		OutputStream outputStream;
		URL url = new URL(down_url);
		HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
		httpURLConnection.setConnectTimeout(TIMEOUT);
		httpURLConnection.setReadTimeout(TIMEOUT);
		totalSize = httpURLConnection.getContentLength();
		if (httpURLConnection.getResponseCode() == 404) {
			throw new Exception("fail!");					
		}
		
		inputStream = httpURLConnection.getInputStream();
		outputStream = new FileOutputStream(file, false);// �ļ������?ǵ�
		byte buffer[] = new byte[1024];
		int readsize = 0;
		
		while ((readsize = inputStream.read(buffer)) != -1) {
			if (httpURLConnection.getResponseCode() == 404) {
				notificationManager.cancel(R.layout.notification_item);
				throw new Exception("fail!");					
			}					
			outputStream.write(buffer, 0, readsize);
			downloadCount += readsize;
			if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) {
				if(jud)
				{
					updateCount += down_step;
					contentView.setTextViewText(R.id.notificationPercent,updateCount + "%");
					contentView.setProgressBar(R.id.notificationProgress, 100,updateCount, false);			
					notification.contentView = contentView;
					notificationManager.notify(R.layout.notification_item, notification);	
				}
				else
				{
					notificationManager.cancel(R.layout.notification_item);
					inputStream.close();
					outputStream.close();
				}
			}
		}
		if (httpURLConnection != null) {
			httpURLConnection.disconnect();
		}
		inputStream.close();
		outputStream.close();
		return downloadCount;
	}
	@Override 
	 public void onDestroy() 
	 { 
		//getApplicationContext().unregisterReceiver(bReceiver);
		super.onDestroy(); 
	 } 

}

MainActivity.java

package com.example.update;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
	private boolean isneedupdate = false;
	private String describe = "";
	private String url = "";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		init();
	}

	public void init() {
		Button tv = (Button) findViewById(R.id.button1);
		Button btn = (Button) findViewById(R.id.update);
		btn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				download();
			}

		});
		tv.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO 自动生成的方法存根
				Intent mIntent = new Intent();
				mIntent.setClass(MainActivity.this, WebActivity.class);
				mIntent.putExtra("url", "http://jq.qq.com/?_wv=1027&k=2AYOmzC");
				MainActivity.this.startActivity(mIntent);
			}

		});
	}

	private void download() {
		new Thread() {
			public void run() {
				try {
					IsNeedUpdate isNeedUpdate = new IsNeedUpdate(
							MainActivity.this);
					isneedupdate = isNeedUpdate.isNeedUpdate(MainActivity.this);
					describe = isNeedUpdate.getDescribe();
					url = isNeedUpdate.getUrl();
					handler.sendEmptyMessage(0);
				} catch (Exception e) {
					e.printStackTrace();
				}
			};
		}.start();
	}

	@SuppressLint("HandlerLeak")
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			// 如果有更新就提示
			if (isneedupdate) {
				ShowUpdateDialog show = new ShowUpdateDialog();
				show.showUpdateDialog(MainActivity.this, describe, url);
			}
		};
	};
}

WebActivity.java

package com.example.update;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class WebActivity extends Activity{
	public static WebView webView;
	private SwipeRefreshLayout swipeLayout;  
	 @SuppressWarnings("deprecation")
	protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.web);
	        init();	
	 }
	 public  void init(){
		   String url=getIntent().getStringExtra("url");
	       webView = (WebView)findViewById(R.id.webView1);	  
	       webView.loadUrl(url);
	 }
}

不过现在有点小bug,只要开始下载后就不能停止了,希望大神帮忙看一下,谢谢

服务器端文件

直接用的txt

XXX
&2.1.9
&1.1更新软件更新
&http://115.159.26.120/androidapp/appupdate/frag2.apk


demo传送门

http://pan.baidu.com/s/1sk8ZI4t
百度云盘提取密码:
抱歉,只有对本文发表过评论才能阅读隐藏内容。

回复百度云盘密码可见