android_apk的在线安装,除了要设计Android 客户端的代码外,还要搭建服务器的代码,仿真实现中Android软件的在线升级。

Android  客户端的代码截图如下。

MainActivity

package com.example.f03_packmanager;import java.io.File;
import java.util.concurrent.ExecutionException;import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;public class MainActivity extends Activity {// 先在文件清单添加获取网络访问权限和准许读写sdcard的permission;private Button button;private ProgressDialog dialog;// 查询版本更新信息的进度对话框private String messagePath = "http://111.0.124.108:8080/http/servlet/Install";// 获取版本更新的URLprivate Message message;private PackUtiles packUtiles;// 获取当前版本信息的封装类private AlertDialog.Builder builder;// 下载更新的对话框@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);dialog = new ProgressDialog(MainActivity.this);dialog.setTitle("提示");dialog.setMessage("download.....");builder = new AlertDialog.Builder(MainActivity.this);builder.setTitle("下载更新");builder.setMessage("是否下载最新的版本?");builder.setCancelable(false);// 设置不能随意关闭提示下载更新的对话框button = (Button) this.findViewById(R.id.button1);packUtiles = new PackUtiles(MainActivity.this);button.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubtry {message = new getAPKUrl().execute(messagePath).get();boolean flag = packUtiles.update(packUtiles.getVersion(),message.getVsersionCode());Log.i("tag", "------->" + flag);if (flag) {builder.setPositiveButton("确定", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stubnew downLoadAPK().execute(message.getApkUrl());}});builder.setNegativeButton("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface arg0, int arg1) {// TODO Auto-generated method stub}});builder.create().show();}} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ExecutionException e) {// TODO Auto-generated catch blocke.printStackTrace();}}});}// 获取版本更新信息的异步任务public class getAPKUrl extends AsyncTask<String, Void, Message> {@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();dialog.show();}@Overrideprotected Message doInBackground(String... params) {// TODO Auto-generated method stubreturn HttpUtiles.getMessage(params[0]);}@Overrideprotected void onPostExecute(Message result) {// TODO Auto-generated method stubsuper.onPostExecute(result);dialog.dismiss();}}public class downLoadAPK extends AsyncTask<String, Void, Void> {@Overrideprotected void onPreExecute() {// TODO Auto-generated method stubsuper.onPreExecute();}@Overrideprotected Void doInBackground(String... params) {// TODO Auto-generated method stubString uri=HttpUtiles.downLoadApk(params[0]);Log.i("TAG2", "-------->"+uri);//通过文件路径安装指定版本Uri uri2=Uri.fromFile(new File(uri));Intent intent=new Intent(Intent.ACTION_VIEW);intent.setDataAndType(uri2, "application/vnd.android.package-archive");startActivity(intent);return null;}@Overrideprotected void onPostExecute(Void result) {// TODO Auto-generated method stubsuper.onPostExecute(result);}}}

HttpUtiles获取服务器的版本信息,一个方法为以json格式获取版本的数据,一个为下载最新的版本到sdcard中

package com.example.f03_packmanager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;import android.os.Environment;
import android.util.Log;public class HttpUtiles {//下载版本信息,格式为jsonpublic static Message getMessage(String path) {Message message = new Message();HttpClient client = new DefaultHttpClient();HttpPost httpPost = new HttpPost(path);try {HttpResponse httpResponse = client.execute(httpPost);if(httpResponse.getStatusLine().getStatusCode()==200){String json=EntityUtils.toString(httpResponse.getEntity());try {JSONObject  jsonObject=new JSONObject(json).getJSONObject("message");message.setVsersionCode(jsonObject.getInt("vsersionCode"));message.setApkUrl(jsonObject.getString("apkUrl"));} catch (JSONException e) {// TODO Auto-generated catch blocke.printStackTrace();}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return message;}//下载指定版本到sdcard中public static String downLoadApk(String path){byte[]data=null;String uri=null;HttpClient client = new DefaultHttpClient();HttpPost httpPost = new HttpPost(path);FileOutputStream fileOutputStream=null;try {HttpResponse httpResponse = client.execute(httpPost);if(httpResponse.getStatusLine().getStatusCode()==200){data=EntityUtils.toByteArray(httpResponse.getEntity());if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){File file=Environment.getExternalStorageDirectory();String name=path.substring(path.lastIndexOf("/")+1,path.length());fileOutputStream=new FileOutputStream(new File(file, name));fileOutputStream.write(data, 0, data.length);uri=file.getAbsolutePath()+"/"+name;}}} catch (ClientProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}finally{if(fileOutputStream!=null){try {fileOutputStream.close();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}Log.i("HTTP", "-------->"+uri);return uri;}}

Message类指定数据返回的格式

package com.example.f03_packmanager;public class Message {private int vsersionCode;private String apkUrl;public int getVsersionCode() {return vsersionCode;}public void setVsersionCode(int vsersionCode) {this.vsersionCode = vsersionCode;}public String getApkUrl() {return apkUrl;}public void setApkUrl(String apkUrl) {this.apkUrl = apkUrl;}@Overridepublic String toString() {return "Message [vsersionCode=" + vsersionCode + ", apkUrl=" + apkUrl+ "]";}}

PackUtilse获取软件当前的版本信息

package com.example.f03_packmanager;import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;public class PackUtiles {private Context context;private PackageManager manager;private PackageInfo info;public PackUtiles(Context context) {// TODO Auto-generated constructor stubthis.context = context;initDate();}public void initDate() {manager = context.getPackageManager();try {info = manager.getPackageInfo(context.getPackageName(),PackageManager.GET_ACTIVITIES);} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke.printStackTrace();}}public int getVersion() {return info.versionCode;}public String getVersionName(){return info.versionName;}//比较本地版本和服务器的版本号的大小public boolean update(int oldVersion,int newVersion){boolean flag=newVersion>oldVersion?true:false;return flag;}
} 

到此Android的代码就编写完成了,下面我们来介绍一下服务器端的代码,事先要导入json的jar包,另外一点注意的是所有的http地址在自己使用的时候都记得改成自己笔记本的ip地址,此外别忘了把要更新的软件apk放在webroot目录下。

package com.login.install;import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONSerializer;public class Install extends HttpServlet {/*** Constructor of the object.*/public Install() {super();}/*** Destruction of the servlet. <br>*/public void destroy() {super.destroy(); // Just puts "destroy" string in log// Put your code here}/*** The doGet method of the servlet. <br>** This method is called when a form has its tag value method equals to get.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {this.doPost(request, response);}/*** The doPost method of the servlet. <br>** This method is called when a form has its tag value method equals to post.* * @param request the request send by the client to the server* @param response the response send by the server to the client* @throws ServletException if an error occurred* @throws IOException if an error occurred*/public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();Message message=new Message();message.setVsersionCode(2);message.setApkUrl("http://111.0.124.108:8080/http/F03_PackManager.apk");Map<String, Object> map=new HashMap<String, Object>();map.put("message", message);out.print(JSONSerializer.toJSON(map));out.flush();out.close();}/*** Initialization of the servlet. <br>** @throws ServletException if an error occurs*/public void init() throws ServletException {// Put your code here}}

Android开发之android_apk 在线安装(源代码分享)相关推荐

  1. Android开发之adb命令安装apk的问题

    众所周知,有时候我们只有apk安装包不一定可以直接在AS跑起来,所以有了adb命令安装 使用adb命令的前提: 1.你的首先配置adb的环境变量查看环境变量配置方法 2.配置好后请检查是否配置成功?如 ...

  2. android 统计app使用时间,android开发之app在线时长统计sdk开发

    引言: 很多app的在线时长统计都是通过在activity的生命周期中埋点来完成的.我这里既然是封装成sdk,当然就不能这样来了.封装sdk的规则,我想大家都清楚,入参尽量少,回调尽量全,权限尽量不要 ...

  3. android 图库分析,Android开发之ImageSwitcher相册功能实例分析

    本文实例讲述了Android开发之ImageSwitcher相册功能.分享给大家供大家参考,具体如下: 简介: 1.ImageSwitcher是viewSwitcher的子类,所以ImageSwitc ...

  4. Android 开发之Windows环境下Android Studio安装和使用教程(图文详细步骤)

    鉴于谷歌最新推出的Android Studio备受开发者的推崇,所以也跟着体验一下. 一.介绍Android Studio  Android Studio 是一个Android开发环境,基于Intel ...

  5. android 监听安装来源_Flutter插件开发之APK自动安装

    点击上方的终端研发部,右上角选择"设为星标" 每日早9点半,技术文章准时送上 公众号后台回复"学习",获取作者独家秘制精品资料 往期文章 记五月的一个Andro ...

  6. android 分享元素,Android开发之5.0activity跳转时共享元素的使用方法

    在两个activity中的xml文件中编写下面的ImageView,主要的就是transitionName属性必须使用相同的属性. android:id="@+id/item_image&q ...

  7. android开发集成flash,Android开发之Adobe flash操作工具类

    本文实例讲述了Android开发之Adobe flash操作工具类.分享给大家供大家参考,具体如下: public class AdobeUtil { /** * 安装flash插件 */ publi ...

  8. 【原作者:吴秦(Tyler)http://www.cnblogs.com/skynet/archive/2010/04/12/1709892.html】Android开发之旅:环境搭建及HelloWo

    Android开发之旅:环境搭建及HelloWorld 2010-04-12 00:45 by 吴秦, 801360 阅读, 138 评论, 收藏, 编辑 --工欲善其事必先利其器 引言 本系列适合0 ...

  9. android studio输入框下划线,Android开发之TextView的下划线添加

    Android开发之TextView高级应用 Android开发之TextView高级应用 我们平时使用TextView往往让它作为一个显示文字的容器,但TextView的功能并不局限于此.以下就和大 ...

最新文章

  1. FastDFS安装与使用
  2. 转-Redis学习手册(目录)
  3. 【五线谱】音高表示 ( 低音谱号 | C1 36 音符音高表示 | C2 48 音符音高表示 | C3 60 音符音高表示 )
  4. php点菜系统开题报告,点餐管理系统的设计与实现-开题报告
  5. mssql 查询无记录时sum_只会使用Sum函数求和,那就真的Out了,不信你试试Sumif、Sumifs、Sumproduct等...
  6. 'Request' object has no attribute 'META'报错解决
  7. python学习day32 黏包 struct模块
  8. Java基础-序列化和反序列化
  9. 思科Catalyst1900交换机上速配VLAN
  10. Springboot项目启动的三种方式
  11. E-Prime 软件中常用的 inline 语句
  12. 什么是工序分析法?工序分析的方法和实施步骤有哪些
  13. IDEA中MyBatis插件的安装及使用
  14. 网页播放 .m3u8 视频文件
  15. 神经元的结构示意图手绘,神经元的结构图手绘
  16. Secondary NameNode工作原理
  17. 【转】​“八段锦”养生:通经络,补气血,简单8个动作调理全身脏腑!
  18. 熟女给老实木讷男孩的恋爱建议(转帖)
  19. 然而大部分工程师的期权并没有什么用
  20. oracle 设行宽,Oracle设置SQLPlus结果显示的宽度,ORACLE sqlplus提示符设置

热门文章

  1. python编写函数、计算三个数的最大公约数_python 函数求两个数的最大公约数和最小公倍数...
  2. 区域填充与击中击不中变换
  3. 阿里云平台注册与使用Linux
  4. vc中GetDlgItem用法
  5. python下载pip脚本显示file_generateScriptFile.py脚本使用过程中遇到的问题及解决
  6. Linux内核调试 - 一般人儿我都不告诉他(一)【转】
  7. Python基础班每日整理(三)
  8. python笔记6--编码
  9. 荣耀9将要回归金属材质,网友直呼:看着就很贵
  10. 加锁查询 FOR UPDATE 解决表格查询极慢的问题