下载android应用有两种表现形式:一种是交给Android系统的下载管理器;另一种是自己去监控下载。

1.使用Android下载管理器下载应用并安装

public class UpdateService extends Service {// 安卓系统下载管理类DownloadManager manager;// 接收下载完的广播DownloadCompleteReceiver receiver;// 初始化下载器private void initDownManager(String url) {manager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);receiver = new DownloadCompleteReceiver();//设置下载地址DownloadManager.Request down = new DownloadManager.Request(Uri.parse(url));// 设置允许使用的网络类型,这里是移动网络和wifi都可以down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE| DownloadManager.Request.NETWORK_WIFI);// 下载时,通知栏显示途中down.setNotificationVisibility(Request.VISIBILITY_VISIBLE);// 显示下载界面down.setVisibleInDownloadsUi(true);// 设置下载后文件存放的位置down.setDestinationInExternalFilesDir(this,Environment.DIRECTORY_DOWNLOADS, "update.apk");// 将下载请求放入队列manager.enqueue(down);//注册下载广播registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {String url= intent.getStringExtra("url");// 调用下载initDownManager(url);return 0;}@Overridepublic IBinder onBind(Intent intent) {return null;}@Overridepublic void onDestroy() {// 注销下载广播if (receiver != null)unregisterReceiver(receiver);super.onDestroy();}// 接受下载完成后的intentclass DownloadCompleteReceiver extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {//判断是否下载完成的广播if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {System.out.println("download complete!");//获取下载的文件idlong downId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1);//自动安装apkinstallAPK(manager.getUriForDownloadedFile(downId));//停止服务并关闭广播UpdateService.this.stopSelf();}}/*** 安装apk文件*/private void installAPK(Uri apk) {// 通过Intent安装APK文件Intent intents = new Intent();System.out.println("auto install");intents.setAction("android.intent.action.VIEW");intents.addCategory("android.intent.category.DEFAULT");intents.setType("application/vnd.android.package-archive");intents.setData(apk);intents.setDataAndType(apk,"application/vnd.android.package-archive");intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);//android.os.Process.killProcess(android.os.Process.myPid());// 有的设备不加上这句的话在apk安装完成之后点击单开始可能会崩溃startActivity(intents);}}
}

2. 自己监控下载。

public class UpdateDialog extends Dialog implements OnClickListener{Button download,cancel;String apkurl="http://....../";String savePath="/**/**/update/";String saveFileName=savePath+"/adf.apk";
<pre name="code" class="java">        ProgressBar mProgress;//进度条Context mContext;
<span style="font-size:24px;"></span><pre name="code" class="java">        private static final int DOWN_UPDATE = 1;//下载更新private static final int DOWN_OVER = 2;//下载完成private static final String TAG = "UpdateManager";private int progress;//进度private Thread downLoadThread;//下载线程public static boolean interceptFlag = false;//是否中断
public UpdateDialog(Context context,String apkurl)
{
super(context);this.apkurl+=apkurlmContext=context;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.update_dialog);
download=(Button)findViewById(R.id.down);
cancel=(Button)findViewById(R.id.downcan);
mProgress=(ProgressBar)findViewById(R.id.progress_update);
download.setOnClickListener(this);
cancel.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.down://点击下载
downloadApk();
dismiss();
break;
case R.id.downcan://取消下载
interceptFlag =true;
dismiss();
break;
default:
break;
}}
/** * 下载apk */
private void downloadApk()
{
downLoadThread = new Thread(mdownApkRunnable);
downLoadThread.start();
}
///** * 安装apk */
private void installApk()
{
File apkfile = new File(saveFileName);
if (!apkfile.exists())
{
return;
}
Intent i = new Intent();
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.DEFAULT");
i.setType("application/vnd.android.package-archive");
i.setData(Uri.parse("file://" + apkfile.toString()));
i.setDataAndType(Uri.parse("file://" + apkfile.toString()),"application/vnd.android.package-archive");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);mContext.startActivity(i);
}
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)
{}
catch (IOException e)
{}}};
private Handler mHandler = new Handler()
{
public void handleMessage(Message msg)
{
switch (msg.what) {
case DOWN_UPDATE:
mProgress.setProgress(progress);
break;
case DOWN_OVER:
//下载完成
dismiss();
installApk();
break;
default:break;
}};};}

Android 应用更新和在服务器下载android应用相关推荐

  1. android 清华镜像,清华镜像网站下载android源码并编译

    8种机械键盘轴体对比 本人程序员,要买一个写代码的键盘,请问红轴和茶轴怎么选? 下载android源码方法: 我的系统是ubuntu 18.04,主要参考了blog通过清华大学镜像下载Android源 ...

  2. android项目中使用的服务器上,android 开发中使用okhttp上传文件到服务器

    开发android手机客户端,常常会需要上传文件到服务器,比如:你手机里的照片. 使用okhttp会是一个很好的选择.它使用很简单,而且运行效率也很高. 首先,在 app/build.gradle 的 ...

  3. android原生农场壁纸,Android 6.0高清壁纸下载-Android 6.0原生壁纸高清免费打包下载-东坡下载...

    android 6.0在现在是很多的安卓手机用户都是升级到这个版本的,那么你需要一些适合这个版本的高清主题壁纸吗?想要的话现在就赶快来下载吧! android 6.0新特性 新特性一:App Perm ...

  4. android 动态更新配置文件,基于DX的Android动态更新技术

    原标题:基于DX的Android动态更新技术 转自:文/Mob开发者平台 技术副总监 余勋杰 DX简介 安卓程序的主要代码是java 代码,不过由于安卓系统不直接使用sun的jvm,所以从javac编 ...

  5. 简书Android客户端更新日志1504010-离线下载

    时间悄悄溜进了四月,这是一个草长莺飞.万物复苏的季节,小动物们都忙着繁衍下一代,简书君却还苦逼的坐在办公室里感叹岁月这把杀猪的刀.说到四月不得不提的就是欢乐的愚人节,本次愚人节简书君也和大家开了一个小 ...

  6. android上传文件至服务器(android端+服务器端)

    引言:本来android文件上传的博客在网上挺多的,不过好些都只是有前台android端的上传,并没有后台服务器端的接收.而且自己写的时候也确实遇见了一些之前没注意到的地方,写出来也算是给自己提个醒. ...

  7. 谷歌Android无障碍套件,安卓无障碍套件下载-Android无障碍套件最新版下载v8.2.0.324286243_游戏369...

    安卓无障碍套件(Android Accessibility Suite)是一款包含一系列无障碍应用的app,用户仅通过开关即可控制安卓设备,朗读屏幕上的内容,使用这个大型屏幕菜单来锁定手机.控制音量和 ...

  8. android o更新设备,MOTO可升级Android O设备清单:有你手机吗

    据外媒报道,本周二谷歌正式公布了Android O最后一个开发者预览版的发布,这意味着Android O正式版即将上线.更迅速的是,已经有网友贴出了摩托罗拉的非官方设备升级名单. MOTO可升级And ...

  9. 谷歌tts android手机自带引擎,自动下载android TTS引擎

    Is there a way to install a language automatically? 是的,但这不会自动发生(未经用户同意),如docs所述: Since the installat ...

最新文章

  1. Java数据类型及变量作业_day02、Java变量与数据类型
  2. 《跃迁 从技术到管理的硅谷路径》读后感
  3. [转载]在线文档预览方案-Office Web Apps
  4. dede如何给dede_sys_enum添加字段father
  5. [iOS] Win8下在Vmware11中安装使用苹果系统OS X 10.10
  6. [html] html5的游戏引擎你了解多少?都有哪些比较好用的引擎呢?
  7. MyEclipse+Tomcat 启动时出现 configuration error occured during startup错误的解决方法
  8. js $.ajax stop,jQuery.ajaxStop() 函数详解
  9. AgileEAS.NET之数据关系映射ORM
  10. 2018北大计算机复试线,北京大学历年考研复试分数线_2018考研分数线
  11. python基础学习笔记3
  12. HDU-1671 Phone List
  13. 2005年1月-2008年10月雅思A类(学术类)作文 TASK 2 考题汇总(10月4日更新)
  14. 【Fiddler抓包】Fiddler基础用法-基于Fiddler5中文汉化版
  15. 2G到5G系统的横向比较(1)多址方式与调制方式
  16. 罗永浩曾想自杀,戴威债务缠身仍不认输......这是无数创业者的生存现状
  17. python搜索网页关键词_新闻网页Python爬虫(jieba分词+关键词搜索排序)
  18. 使用PMOS管构建电源延时供电电路
  19. Android中你不得不知的几个问题及解决方法
  20. python 视频加字幕_【小技巧】用Python给你的视频添加字幕

热门文章

  1. 前端学习(1151):let经典面试题1
  2. 前端学习(580):打开开发者工具
  3. 前端学习(221):字体属性
  4. java 虚类private 继承_Java经典面试36题和答案
  5. 常见的数据增强项目和论文介绍
  6. 快速入门 Jupyter notebook
  7. tomcat多域名访问
  8. 三次样条插值 cubic spline interpolation
  9. ASP.NET知识结构
  10. easyui Combotree 怎么加载数据 支持多选