安卓工具类(安卓升级代码)

安卓工具类(安卓升级代码)2、如何获取本地客户端的版本信息 如下参考代码:[java] private int getAPKVersion; PackageInfo i

大家好,欢迎来到IT知识分享网。安卓工具类(安卓升级代码)

获取资源,然后生成JSON字串返回客户端处理。 注:当客户端版本有更新,服务器端只要把APK文件拷贝到APK目录,然后更新apkVersion.properties文件中的信息就可以了,切记。

客户端设计:

1、 客户端首先获取服务器的版本信息(http方式获取)。

2、 如何获取本地客户端的版本信息 如下参考代码:

[java]

private int getAPKVersion(){

//APK版本判断

int sdcardVersion = 0;

String apkFilePath=”sdcard/demo.apk”; //安装包路径

PackageManager pm = getPackageManager();

PackageInfo info = pm.getPackageArchiveInfo(apkFilePath, PackageManager.GET_ACTIVITIES);

if(info != null){

sdcardVersion=info.versionCode; //得到版本信息

Log.v(TAG, “Version=”+sdcardVersion);

}

return sdcardVersion;

}

3、 版本比较,如果版本相同,则不执行更新,不同才进行更新操作。 这里插入客户端版本设置介绍: 客户端版本设置在AndroidManifest.xml文件中,里面有两个属性可进行版本信息设置, android:versionCode=”1″ 版本号 android:versionName=”1.1″ 版本名称 这个版本号需要和服务器端对应。

4、 需要的权限设置

[plain]

Sdcard访问权限: uses-permission android:name=”android.permission.WRITE_EXTERNAL_STORAGE”

访问网络权限: uses-permission android:name=”android.permission.INTERNET”

5、 更新安装 当用户点击应用时执行检查更新。相关代码参考:

//弹出框提示

[java]

public Handler handler = new Handler() {

public void handleMessage(Message msg) {

super.handleMessage(msg);

Dialog dialog = new AlertDialog.Builder(MainActivity.this).setTitle(“系统更新”).setMessage(“发现新版本,请更新!”)

// 设置内容.setPositiveButton(“确定”,// 设置确定按钮new DialogInterface.OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

pBar = new ProgressDialog(MainActivity.this);

pBar.setTitle(“正在下载”);pBar.setMessage(“请稍候…”);

pBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);downFile(apkPath);}}).setNegativeButton(“取消”, new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int whichButton) {

// 点击”取消”按钮操作}}).create();// 创建

// 显示对话框

dialog.show();

}

};

//下载

[java]

public void downFile(final String url) {

pBar.show();

new Thread() {

public void run() {

HttpClient client = new DefaultHttpClient();

// params[0]代表连接的

urlHttpGet get = new HttpGet(url);

HttpResponse response;

try {

response = client.execute(get);

HttpEntity entity = response.getEntity();

long length = entity.getContentLength();

InputStream is = entity.getContent();

FileOutputStream fileOutputStream = null;

if (is != null) {

File file = new File(Environment.getExternalStorageDirectory(),”demo.apk”);

fileOutputStream = new FileOutputStream(file);

byte[] buf = new byte[1024];

int ch = -1;

int count = 0;

while ((ch = is.read(buf)) != -1) {

// baos.write(buf, 0, ch);

fileOutputStream.write(buf, 0, ch);

count += ch;if (length > 0) {}

}

}

fileOutputStream.flush();

if (fileOutputStream != null) {

fileOutputStream.close();

}

down();

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

}.start();

}

public void down() {

handler.post(new Runnable()

{

public void run() {

pBar.cancel();

update();

}});

}

//更新升级

[java]

public void update() {

Intent intent = new Intent(Intent.ACTION_VIEW);

intent.setDataAndType(Uri.fromFile(new File(“/sdcard/demo.apk”)),”application/vnd.android.package-archive”);

startActivity(intent);

}

第二步:新建一个UpdateManager.java类,负责软件更新功能模块,代码如下:

[java] view plaincopy

package com.tutor.update;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import android.app.AlertDialog;

import android.app.Dialog;

import android.app.AlertDialog.Builder;

import android.content.Context;

import android.content.DialogInterface;

import android.content.Intent;

import android.content.DialogInterface.OnClickListener;

import android.net.Uri;

import android.os.Handler;

import android.os.Message;

import android.view.LayoutInflater;

import android.view.View;

import android.widget.ProgressBar;

public class UpdateManager {

private Context mContext;

//提示语

private String updateMsg = “有最新的软件包哦,亲快下载吧~”;

//返回的安装包url

private String apkUrl = “http://softfile.3g.qq.com:8080/msoft/179/24659/43549/qq_hd_mini_1.4.apk”;

private Dialog noticeDialog;

private Dialog downloadDialog;

/* 下载包安装路径 */

private static final String savePath = “/sdcard/updatedemo/”;

private static final String saveFileName = savePath + “UpdateDemoRelease.apk”;

/* 进度条与通知ui刷新的handler和msg常量 */

private ProgressBar mProgress;

private static final int DOWN_UPDATE = 1;

private static final int DOWN_OVER = 2;

private int progress;

private Thread downLoadThread;

private boolean interceptFlag = false;

private Handler mHandler = new Handler(){

public void handleMessage(Message msg) {

switch (msg.what) {

case DOWN_UPDATE:

mProgress.setProgress(progress);

break;

case DOWN_OVER:

installApk();

break;

default:

break;

}

};

};

public UpdateManager(Context context) {

this.mContext = context;

}

//外部接口让主Activity调用

public void checkUpdateInfo(){

showNoticeDialog();

}

private void showNoticeDialog(){

AlertDialog.Builder builder = new Builder(mContext);

builder.setTitle(“软件版本更新”);

builder.setMessage(updateMsg);

builder.setPositiveButton(“下载”, new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

dialog.dismiss();

showDownloadDialog();

}

});

builder.setNegativeButton(“以后再说”, new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

dialog.dismiss();

}

});

noticeDialog = builder.create();

noticeDialog.show();

}

private void showDownloadDialog(){

AlertDialog.Builder builder = new Builder(mContext);

builder.setTitle(“软件版本更新”);

final LayoutInflater inflater = LayoutInflater.from(mContext);

View v = inflater.inflate(R.layout.progress, null);

mProgress = (ProgressBar)v.findViewById(R.id.progress);

builder.setView(v);

builder.setNegativeButton(“取消”, new OnClickListener() {

@Override

public void onClick(DialogInterface dialog, int which) {

dialog.dismiss();

interceptFlag = true;

}

});

downloadDialog = builder.create();

downloadDialog.show();

downloadApk();

}

private Runnable mdownApkRunnable = new Runnable() {

@Override

public void run() {

try {

URL url = new URL(apkUrl);

HttpURLConnection conn = (HttpURLConnection)url.openConnection();

conn.connect();

int length = conn.getContentLength();

InputStream is = conn.getInputStream();

File file = new File(savePath);

if(!file.exists()){

file.mkdir();

}

String apkFile = saveFileName;

File ApkFile = new File(apkFile);

FileOutputStream fos = new FileOutputStream(ApkFile);

int count = 0;

byte buf[] = new byte[1024];

do{

int numread = is.read(buf);

count += numread;

progress =(int)(((float)count / length) * 100);

//更新进度

mHandler.sendEmptyMessage(DOWN_UPDATE);

if(numread <= 0){

//下载完成通知安装

mHandler.sendEmptyMessage(DOWN_OVER);

break;

}

fos.write(buf,0,numread);

}while(!interceptFlag);//点击取消就停止下载.

fos.close();

is.close();

} catch (MalformedURLException e) {

e.printStackTrace();

} catch(IOException e){

e.printStackTrace();

}

}

};

/**

* 下载apk

* @param url

*/

private void downloadApk(){

downLoadThread = new Thread(mdownApkRunnable);

downLoadThread.start();

}

/**

* 安装apk

* @param url

*/

private void installApk(){

File apkfile = new File(saveFileName);

if (!apkfile.exists()) {

return;

}

Intent i = new Intent(Intent.ACTION_VIEW);

i.setDataAndType(Uri.parse(“file://” + apkfile.toString()), “application/vnd.android.package-archive”);

mContext.startActivity(i);

}

}

第三步:在MainActivity.java也就是主Activity调用,代码如下:

[java] view plaincopy

package com.tutor.update;

import android.app.Activity;

import android.os.Bundle;

public class MainAcitivity extends Activity {

private UpdateManager mUpdateManager;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

//这里来检测版本是否需要更新

mUpdateManager = new UpdateManager(this);

mUpdateManager.checkUpdateInfo();

}

}

第四步:添加程序所用的资源与权限:下载的时候用到了ProgressBar,所以事先写了一个progress.xml布局文件,代码如下:

[java] view plaincopy

<?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”>

<ProgressBar

android:id=”@+id/progress”

android:layout_width=”fill_parent”

android:layout_height=”wrap_content”

style=”?android:attr/progressBarStyleHorizontal”

/>

</LinearLayout>

下载的时候用到了网络部分,所以要在AndroidManifest.xml中添加网络权限,代码如下:[java] view plaincopy

<uses-permission android:name=”android.permission.INTERNET” />

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://yundeesoft.com/59114.html

(0)

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

关注微信