Mainactivity
private ProgressBar progressbar1;
// 进度条进度
private int pregress_cont;
private GetVersionCode getcode;
private List<NameValuePair> pair;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getcode = new GetVersionCode();
}
// 点击事件
public void version_check(View view) {
pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("", ""));
new Thread() {
public void run() {
// 这里发送请求
// String str =
// http_post("http://169.254.61.100:8080/1310A/json.txt",pair);
String str = Httputils.http_post("http://www.baidu.com", pair);
Log.i("TAG", "返回结果==" + str);
if (null != str && !str.equals("000")) {
// 这里对返回值进行判断,如果服务器版本大于当前版本,那么久弹出一个框,提示更新
// 因为请求原因,这里直接弹出一个框,选择下载文件
mHandler.sendEmptyMessage(1);
} else {
// 提示用户,请求失败
}
};
}.start();
}
// 展示dialog
public void showwdialog() {
// int code = getcode.getVersionCode(MainActivity.this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("检查更新!");
builder.setMessage("是否下载更新");
builder.setPositiveButton("立即下载", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
showload();
}
}).setNegativeButton("以后再说", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.show();
}
public void showload() {
// 开始下载文件
new Thread() {
public void run() {
Download.loadFile(
"http://gdown.baidu.com/data/wisegame/f98d235e39e29031/baiduxinwen.apk",
mHandler);
};
}.start();
// 弹出是否进入后台下载框
LinearLayout layout = (LinearLayout) LayoutInflater.from(
MainActivity.this).inflate(R.layout.loaddialog, null);
progressbar1 = (ProgressBar) layout.findViewById(R.id.progressbar1);
Builder my_builder = new Builder(MainActivity.this);
my_builder.setView(layout);
my_builder.setPositiveButton("后台下载", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
my_builder.show();
}
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 1:
showwdialog();
break;
case 11:
// 正在下载 设置进度条位置
pregress_cont = msg.arg1;
progressbar1.setProgress(pregress_cont);
break;
case 200:
// 通知安装下载的apk
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "baiduxinwen.apk")),
"application/vnd.android.package-archive");
MainActivity.this.startActivity(intent);
break;
default:
break;
}
};
};
Download
//下载文件
public static void loadFile(String url,Handler mHandler) {
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(url);
HttpResponse response;
try {
response = client.execute(get);
HttpEntity entity = response.getEntity();
float length = entity.getContentLength();
InputStream is = entity.getContent();
FileOutputStream fileOutputStream = null;
if (is != null) {
File file = new File(Environment.getExternalStorageDirectory(),
"baiduxinwen.apk");
fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int ch = -1;
float count = 0;
while ((ch = is.read(buf)) != -1) {
fileOutputStream.write(buf, 0, ch);
count += ch;
// sendMsg(1,(int) (count*100/length));
//正在下载,计算下载大小
int pregress_cont = (int) (((float) count / length) * 100);
Message mes = new Message();
mes.arg1 = pregress_cont;
mes.what= 11;
mHandler.sendMessage(mes);
}
}
//下载完成,发送消息---通知安装
mHandler.sendEmptyMessage(200);
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
// sendMsg(-1,0);
}
}
Httputils
//请求服务器
public static String http_post(String url,List<NameValuePair> pair){
String str = "";
HttpPost httpRequest = new HttpPost(url);
try {
httpRequest.setEntity(new UrlEncodedFormEntity(pair,HTTP.UTF_8));
// HttpResponse httpResponse=new DefaultHttpClient().execute(httpRequest);
HttpResponse response = new DefaultHttpClient().execute(httpRequest);
if(response.getStatusLine().getStatusCode()==200){
str = EntityUtils.toString(response.getEntity());
Log.i("TAG", "请求返回结果==="+str.toString());
}else{
//请求失败返回值
str = "000";
}
} catch (Exception e) {
e.printStackTrace();
//请求失败返回值
str = "000";
}
return str;
}
GetVersionCode
public int getVersionCode(Context context) {
int versionCode = 0;
try{
// 获取软件版本号,
versionCode = context.getPackageManager().getPackageInfo(
"com.bawei.version_update", 0).versionCode;
}catch (NameNotFoundException e) {
e.printStackTrace();
}
return versionCode;
}
main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.bawei.version_update.MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:onClick="version_check"
android:layout_centerVertical="true"
android:text="@string/button" />
</RelativeLayout>
loaddialog.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" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="6dp"
android:layout_marginLeft="4dp"
android:layout_marginTop="10dp"
android:textColor="#000" />
<ProgressBar
android:id="@+id/progressbar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:max="100"
android:progress="0" />
</LinearLayout>
权限
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" >
</uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" >
</uses-permission>