版本升级demo(thread+service+Notification)

11.png  33.png 66.png 

第一步:获取本机app版本:

public int getVerCode(Context _context,String _package) {
int verCode = -1;
try {
verCode = _context.getPackageManager().getPackageInfo(
_package, 0).versionCode;
} catch (NameNotFoundException e) {
}
return verCode;
}

第二步:线程从服务端下载当前版本以及升级提示:

public JSONObject getJsonObject(String Url) {
HttpClient client = new DefaultHttpClient();
StringBuilder sb = new StringBuilder();
String js = null;JSONObject son=null;
HttpGet myget = new HttpGet(Url); 
try {
HttpParams params = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(params, 8000);
HttpResponse response = client.execute(myget);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
for (String s = reader.readLine(); s != null; s = reader.readLine()) {
sb.append(s);
}
js = sb.toString();
son = new JSONObject(js);
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("异常-》下载转化JSON");
return null;
}
return son;
}

第三步:进行版本号对比,若有新版本,进行版本升级提示,builder使用自定义view。

LinearLayout ll = (LinearLayout) LayoutInflater.from(TestVersionUpdateActivity.this).inflate(
R.layout.layout_loadapk, null);
pb = (ProgressBar) ll.findViewById(R.id.down_pb);
tv = (TextView) ll.findViewById(R.id.tv);
Builder builder = new Builder(TestVersionUpdateActivity.this);
builder.setView(ll);builder.setTitle("版本更新进度提示");
builder.setNegativeButton("后台下载",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent intent=new Intent(TestVersionUpdateActivity.this, VersionService.class); 
startService(intent);
dialog.dismiss();
}
});

builder.show();
new Thread() {
public void run() {
loadFile("http://1.nightman.sinaapp.com/test/good.zip");
}
}.start();

第四步,进行更新

public void loadFile(String url) {
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(),
"NightMan.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));
}
}
sendMsg(2,0);
fileOutputStream.flush();
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
sendMsg(-1,0);
}
}
private void sendMsg(int flag,int c) {
Message msg = new Message();
msg.what = flag;msg.arg1=c;
handler.sendMessage(msg);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {// 定义一个Handler,用于处理下载线程与UI间通讯
if (!Thread.currentThread().isInterrupted()) {
switch (msg.what) {
case 1:
pb.setProgress(msg.arg1);
loading_process = msg.arg1;
tv.setText("已为您加载了:" + loading_process + "%");
break;
case 2:
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "NightMan.apk")),
"application/vnd.android.package-archive");
startActivity(intent);
break;
case -1:
String error = msg.getData().getString("error");
Toast.makeText(TestVersionUpdateActivity.this, error, 1).show();
break;
}
}
super.handleMessage(msg);
}
};

后台下载service循环handler

private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// 1为出现,2为隐藏
if(TestVersionUpdateActivity.loading_process>99){
notificationMrg.cancel(0);
stopSelf();
return;
}
if(TestVersionUpdateActivity.loading_process>old_process){
displayNotificationMessage(TestVersionUpdateActivity.loading_process);
}

new Thread() {
public void run() {
isFirstStart=false;
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}.start();
old_process =TestVersionUpdateActivity.loading_process;
}
};

有需要改进的地方望大哥们多踢踢BUG

应部分朋友的需求,这边上一下服务端的代码

服务器端以PHP为例,输出一个JSON格式的字符串
<?php
echo '{        "version":2,
        "content":[{"id":0,"text":"增加了摇一摇自动排列频道的功能"},
{"id":1,"text":"优化了拖拽缓冲的效果"},
{"id":2,"text":"改善了PATH菜单用户体验"},
{"id":3,"text":"添加了更多名人趣事"}
]}
        ';

源码:https://files.cnblogs.com/shanzei/versionUpdate%E7%89%88%E6%9C%AC%E5%8D%87%E7%BA%A7demo%EF%BC%88thread_service_Notification%EF%BC%89.zip

原文:http://www.eoeandroid.com/thread-157060-1-1.html

原文地址:https://www.cnblogs.com/shanzei/p/2456655.html