github项目地址:/
最近自己在做一款APP,需要实现APP版本更新功能,从网上找了许多资料,只找到了关于移动端的实现。经过我的研究,终于实现了比较完整的android APP版本更新功能,在此分享给广大朋友,但是我的ios端还没实现,但是传输是基于的http协议,实现原理应该是大同小异的。接下来进入正文。
PHP后台服务器实现
后台的实现是基于的thinkPHP框架。对于PHP开发框架thinkPHP框架的朋友,只要去官网下载手册,看那么几页,我想你应该就懂了。
接下来直接给出PHP代码实现。
对于这个文件,大家需要修改的便是命名空间。
namespaceAPIController;useThinkController;
至于为什么,大家需要了解下PHP的基础知识,和thinkPHP框架的开发流程就可以了,很快的。
<?phpnamespaceAPI Controller;useThinkController;classServerControllerextendsController {public functionindex(){//$this->show('
娆㈣繋浣跨敤ThinkPHP锛?/p>
[鎮ㄧ幇鍦ㄨ闂殑鏄疕ome妯″潡鐨処ndex鎺у埗鍣?]
这里需要解释的是
functionupdateInfo()
这个方法实现的是获得最近的版本信息。然后和移动端进行匹配
URL地址是:localhost/index.php/API/Server/updateinfo,大家可以根据自己的服务器或者云服务器的IP地址进行修改。
functiondownload(){
这个方法实现的是下载功能,也就是核心方法。移动端需要访问到这个IP地址才能进行文件的下载。
URL地址是:localhost/index.php/API/Server/download,大家可以根据自己的服务器或者云服务器的IP地址进行修改。
关于需要下载的文件路径,我是存放在ubuntu系统的/tmp目录下的
android移动端实现
移动端我直接给出了实现放的类和方法以及活动,就不解释了。
只给出基本的原理
1、从这个URL地址localhost/index.php/API/Server/updateinfo获取最新的版本信息,通过http协议和json协议解析出基本的版本信息,然后存储在UpdateInfo类中,然后和APP的当前版本进行比较,如果有最新版则下载。
2、关于下载,android端的核心实现代码是
newThread() {
public voidrun() {
HttpClient client = newDefaultHttpClient();HttpGet get = newHttpGet(url);HttpResponse response;try{
response = ute(get);HttpEntity entity = Entity();intlength = (int) ContentLength();progressDialog.setMax(length);InputStream is = Content();FileOutputStream fileOutputStream = null;if(is != null) {
File file = newFile(
fileOutputStream.write(buf,0,ch);process += ch;progressDialog.setProgress(process);}
}
fileOutputStream.flush();if(fileOutputStream != null) {
fileOutputStream.close();}
down();} catch(ClientProtocolException e) {
e.printStackTrace();} catch(IOException e) {
e.printStackTrace();}
}
}.start();
而PHP的实现代码是download中的
ob_clean();flush();readfile($file);
至于底层的原理是,readfile方法封装了,http文件传输的基本实现,大家可以百度下,以上两段代码配合,一个客户端,一个服务器,就能够实现基于http文件的传输.
最后给出android端的代码
importandroid.annotation.SuppressLint;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.app.t.DialogInterface;importandroid.os.Bundle;importandroid.os.Environment;importandroid.os.Handler;importandroid.os.Message;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ample.administrator.dongzhiwuapp.R;public classSetActivity extendsActivity {
privateUpdateInfo info;privateProgressDialog progressDialog;//下载进度条窗口UpdateInfoService updateInfoService;@Overrideprotected voidonCreate(Bundle savedInstanceState) {
@Overridepublic voidonClick(View v) {
checkUpdate();}
});}
private voidcheckUpdate(){
newThread() {
public voidrun() {
try{
updateInfoService= newUpdateInfoService(SetActivity.this);info= UpDateInfo();handler1.sendEmptyMessage(0);} catch(Exception e) {
e.printStackTrace();}
};}.start();}
@SuppressLint("HandlerLeak")
privateHandler handler1= newHandler() {
public voidhandleMessage(Message msg) {
if(updateInfoService.isNeedUpdate()) {
showUpdateDialog();}
}
};private voidshowUpdateDialog() {
AlertDialog.Builder builder = newAlertDialog.Builder(this);builder.setIcon(android.R.drawable.ic_dialog_info);builder.setTitle("请升级APP版本至"+ Version());builder.Description());builder.setCancelable(false);builder.setPositiveButton("确定", newDialogInterface.OnClickListener() {
@Overridepublic voidonClick(DialogInterface dialog, intwhich) {
ExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Url());} else{
Toast.makeText(SetActivity.this,"SD卡不可用,请插入SD卡",Toast.LENGTH_SHORT).show();}
}
});builder.setNegativeButton("取消", newDialogInterface.OnClickListener() {
@Overridepublic voidonClick(DialogInterface dialog, intwhich) {
}
});ate().show();}
//进入下载voiddownFile(finalString url) {
progressDialog= newProgressDialog(SetActivity.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setTitle("正在下载");progressDialog.setMessage("请稍后...");progressDialog.setProgress(0);progressDialog.show();updateInfoService.downLoadFile(url,progressDialog,handler1);}
}
importandroid.annotation.SuppressLint;importandroid.app.Activity;importandroid.app.AlertDialog;importandroid.app.t.DialogInterface;importandroid.os.Bundle;importandroid.os.Environment;importandroid.os.Handler;importandroid.os.Message;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ample.administrator.dongzhiwuapp.R;public classSetActivity extendsActivity {
privateUpdateInfo info;privateProgressDialog progressDialog;//下载进度条窗口UpdateInfoService updateInfoService;@Overrideprotected voidonCreate(Bundle savedInstanceState) {
@Overridepublic voidonClick(View v) {
checkUpdate();}
});}
private voidcheckUpdate(){
newThread() {
public voidrun() {
try{
updateInfoService= newUpdateInfoService(SetActivity.this);info= UpDateInfo();handler1.sendEmptyMessage(0);} catch(Exception e) {
e.printStackTrace();}
};}.start();}
@SuppressLint("HandlerLeak")
privateHandler handler1= newHandler() {
public voidhandleMessage(Message msg) {
if(updateInfoService.isNeedUpdate()) {
showUpdateDialog();}
}
};private voidshowUpdateDialog() {
AlertDialog.Builder builder = newAlertDialog.Builder(this);builder.setIcon(android.R.drawable.ic_dialog_info);builder.setTitle("请升级APP版本至"+ Version());builder.Description());builder.setCancelable(false);builder.setPositiveButton("确定", newDialogInterface.OnClickListener() {
@Overridepublic voidonClick(DialogInterface dialog, intwhich) {
ExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
Url());} else{
Toast.makeText(SetActivity.this,"SD卡不可用,请插入SD卡",Toast.LENGTH_SHORT).show();}
}
});builder.setNegativeButton("取消", newDialogInterface.OnClickListener() {
@Overridepublic voidonClick(DialogInterface dialog, intwhich) {
}
});ate().show();}
//进入下载voiddownFile(finalString url) {
progressDialog= newProgressDialog(SetActivity.this);progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);progressDialog.setTitle("正在下载");progressDialog.setMessage("请稍后...");progressDialog.setProgress(0);progressDialog.show();updateInfoService.downLoadFile(url,progressDialog,handler1);}
}
/***获取服务器地址*/public classGetServerUrl{
staticString url="";public staticString getUrl() {
returnurl;}
}
/***版本更新信息类* 1、获取版本字符串信息* 2、设置版本字符串信息* 3、获取版本描述* 4、设置版本描述* 5、获取URL地址* 6、设置URL地址* */public classUpdateInfo
{
privateString version;privateString description;privateString url;publicString getVersion()
{
returnversion;}
public voidsetVersion(String version)
{
this.version= version;}
publicString getDescription()
{
returndescription;}
public voidsetDescription(String description)
{
this.description= description;}
publicString getUrl()
{
returnurl;}
public voidsetUrl(String url)
{
this.url= url;}
}
importandroid.app.t.t.t.pm.t.pm.t.pm.PackageManager.NameNotFoundException;importandroid.Uri;importandroid.os.Environment;importandroid.os.Handler;importandroid.util.Log;importorg.apache.http.HttpEntity;importorg.apache.http.HttpResponse;importorg.apache.http.client.ClientProtocolException;importorg.apache.http.client.HttpClient;importorg.apache.hods.HttpGet;importorg.apache.http.impl.client.DefaultHttpClient;importorg.apache.http.util.EntityUtils;importorg.json.JSONObject;importjava.io.File;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;public classUpdateInfoService {
ProgressDialog progressDialog;Handler handler;Context context;UpdateInfo updateInfo;publicUpdateInfoService(Context context){
/**获取更新信息*版本信息存储在服务器的文件中*更新信息包括:* 1、版本信息* 2、最新版本具体描述* 3、下载地址** */publicUpdateInfo getUpDateInfo() throwsException {
HttpClient httpClient = newDefaultHttpClient();HttpGet httpGet = newHttpGet("localhost/index.php/API/Server/updateInfo");HttpResponse httpResponse = ute(httpGet);UpdateInfo updateInfo = newUpdateInfo();StatusLine().getStatusCode() == 200)//请求相应成功{
HttpEntity entity = Entity();String response = String(entity,"utf-8");JSONObject jsonObject=newJSONObject(response);Log.d("dsdsada","getUpDateInfo: "+response);updateInfo.String("version"));updateInfo.String("description"));updateInfo.String("url"));this.updateInfo= updateInfo;returnupdateInfo;}
updateInfo.setVersion("");updateInfo.setDescription("");updateInfo.setUrl("");this.updateInfo= updateInfo;returnupdateInfo;}
/**判断是否需要更新*/public booleanisNeedUpdate(){
String new_version = Version();String now_version="";try{
PackageManager packageManager = PackageManager();PackageInfo packageInfo = PackageInfo(
e.printStackTrace();}
if(new_version.equals(now_version)) {
return false;} else{
return true;}
}
/***下载文件* */public voiddownLoadFile(finalString url,finalProgressDialog pDialog,Handler h){
progressDialog=pDialog;handler=h;newThread() {
public voidrun() {
HttpClient client = newDefaultHttpClient();HttpGet get = newHttpGet(url);HttpResponse response;try{
response = ute(get);HttpEntity entity = Entity();intlength = (int) ContentLength();progressDialog.setMax(length);InputStream is = Content();FileOutputStream fileOutputStream = null;if(is != null) {
File file = newFile(
fileOutputStream.write(buf,0,ch);process += ch;progressDialog.setProgress(process);}
}
fileOutputStream.flush();if(fileOutputStream != null) {
fileOutputStream.close();}
down();} catch(ClientProtocolException e) {
e.printStackTrace();} catch(IOException e) {
e.printStackTrace();}
}
}.start();}
//下载完毕,退出下载,进入安装APP步骤voiddown() {
handler.post(newRunnable() {
public voidrun() {
progressDialog.cancel();update();}
});}
//安装最新版本APPvoidupdate() {
Intent intent = newIntent(Intent.ACTION_VIEW);intent.setDataAndType(Uri.fromFile(newFile(Environment
.getExternalStorageDirectory(),"Test.apk")),"application/vnd.android.package-archive");context.startActivity(intent);}
}
github项目地址:/
本文发布于:2024-01-30 01:46:13,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170655037918356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |