今天说一下AndroID中下载App到手机中并自动安装,啥也不说了先上效果图了!
上面呢是下载中的一个图片和下载后会自动提示你安装的一个图片,二话不说,这接开代码吧!
首先来一个下布局:
<?xml version="1.0" enCoding="utf-8"?> <relativeLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" xmlns:app="http://schemas.androID.com/apk/res-auto" xmlns:tools="http://schemas.androID.com/tools" androID:layout_wIDth="match_parent" androID:layout_height="match_parent" tools:context="zhangtao.bwIE.com.continutransform.MainActivity"> <Progressbar androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/progress" androID:max="100" /> <TextVIEw androID:layout_wIDth="wrap_content" androID:layout_height="wrap_content" androID:layout_centerHorizontal="true" androID:textSize="22sp" androID:text="" androID:ID="@+ID/pro_text" androID:layout_below="@ID/progress" /> <button androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/start_btn" androID:text="开始下载" androID:layout_below="@ID/pro_text" /> <button androID:layout_wIDth="match_parent" androID:layout_height="wrap_content" androID:ID="@+ID/stop_btn" androID:text="停止下载" androID:layout_below="@ID/start_btn" /> </relativeLayout>
布局随便写了,只要是你想要的布局
然后我么来一个接口,用来帮助我么将要写的下载工具类传输数据的:
package Download; public interface DownloadListener { voID startDownload(); voID stopDownload(); voID finishDownload(); voID downloadProgress(long progress); }
这个接口写了4个接口方法,分别是开始下载、停止下载、完成下载以及下载是的进度。
接下来就是写下载工具类了,下载呢就使用Okhttp进行请求网络数据了,这里把这个工具类写成单利模式,方便使用!
package Download; import androID.text.TextUtils; import androID.util.Log; import java.io.file; import java.io.IOException; import java.io.inputStream; import java.io.RandomAccessfile; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkhttpClIEnt; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; public class DownloadUtils { private static volatile DownloadUtils instance; private final OkhttpClIEnt clIEnt; private DownloadListener mListener; private file file; private String fileabsolutePath; public file downloadfile; private long startposition; private Call call; public DownloadUtils() { clIEnt = new OkhttpClIEnt(); } public voID setListener(DownloadListener Listener) { this.mListener = Listener; } /** * 初始化下载父路径 * @return */ public voID initDownload(String path) { file = new file(path); if(!file.getParentfile().exists()) { file.getParentfile().mkdir(); } if(!file.exists()) { try { file.createNewfile(); } catch (IOException e) { e.printstacktrace(); } } fileabsolutePath = file.getabsolutePath(); Log.d("zzz",fileabsolutePath.toString()); } public static DownloadUtils getInstance() { if(instance == null) { synchronized (DownloadUtils.class) { if(instance == null) { instance = new DownloadUtils(); } } } return instance; } public voID startDownload(String url) { if(TextUtils.isEmpty(url)) { return ; } if(url.contains(".")) { String typename = url.substring(url.lastIndexOf(".") + 1); if(url.contains("/")) { String filename = url.substring(url.lastIndexOf("/") + 1,url.lastIndexOf(".")); String fn = filename+"."+typename; downloadfile = new file(this.file,fn); Log.d("zzz","downloadfile"+downloadfile.toString()); } } startposition = 0; if(downloadfile.exists()) { startposition = downloadfile.length(); } final Request request = new Request.Builder() .addheader("RANGE","bytes="+startposition+"-") .url(url) .build(); call = clIEnt.newCall(request); call.enqueue(new Callback() { @OverrIDe public voID onFailure(Call call,IOException e) { } @OverrIDe public voID onResponse(Call call,Response response) throws IOException { mListener.startDownload(); ResponseBody body = response.body(); // startposition long totalLength = body.contentLength() ; Log.d("zzz","totalLength: " + totalLength + "----"); inputStream is = body.byteStream(); byte[] bytes = new byte[2048]; int len = 0; long totalNum = startposition; RandomAccessfile raf = new RandomAccessfile(downloadfile,"rw"); while ((len = is.read(bytes,bytes.length)) != -1) { raf.seek(totalNum); raf.write(bytes,len); totalNum +=len; mListener.downloadProgress(totalNum * 100 / totalLength); } mListener.finishDownload(); body.close(); } }); } public voID stopDownload() { mListener.startDownload(); if(call != null && call.isExecuted()) { call.cancel(); } } }
这里做断点下载是使用了RandomAccessfile,大家可以网上去了解一下RandomAccessfile的作用。
下面是主界面的功能实现和调用,基本就是些获取控件和调用刚才写好的工具类:
package zhangtao.bwIE.com.continutransform; import androID.content.Intent; import androID.net.Uri; import androID.os.Bundle; import androID.os.Environment; import androID.support.v7.app.AppCompatActivity; import androID.vIEw.VIEw; import androID.Widget.button; import androID.Widget.Progressbar; import androID.Widget.TextVIEw; import java.io.file; import Download.DownloadListener; import Download.DownloadUtils; public class MainActivity extends AppCompatActivity implements VIEw.OnClickListener{ private TextVIEw pro_text; private button start_btn; private button stop_btn; private String downloadUrl = "http://d.988wan.com/zft/qmzft32_988wan_01.apk"; private String path = "/ZhangTao/"; private Progressbar pro_bar; @OverrIDe protected voID onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentVIEw(R.layout.activity_main); initVIEw(); setonClick(); if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { file storageDirectory = Environment.getExternalStorageDirectory(); final String absolutePath = storageDirectory.getabsolutePath(); path = absolutePath + path; DownloadUtils.getInstance().initDownload(path); DownloadUtils.getInstance().setListener(new DownloadListener() { @OverrIDe public voID startDownload() { } @OverrIDe public voID stopDownload() { } @OverrIDe public voID finishDownload() { file downloadfile = DownloadUtils.getInstance().downloadfile; installApk(downloadfile); } @OverrIDe public voID downloadProgress(final long progress) { runOnUiThread(new Runnable() { @OverrIDe public voID run() { pro_bar.setProgress((int) progress); pro_text.setText(progress+"%"); } }); } }); } } private voID initVIEw() { pro_text = (TextVIEw) findVIEwByID(R.ID.pro_text); start_btn = (button) findVIEwByID(R.ID.start_btn); stop_btn = (button) findVIEwByID(R.ID.stop_btn); pro_bar = (Progressbar) findVIEwByID(R.ID.progress); } private voID setonClick() { start_btn.setonClickListener(this); stop_btn.setonClickListener(this); } @OverrIDe public voID onClick(VIEw vIEw) { switch (vIEw.getID()) { case R.ID.start_btn: DownloadUtils.getInstance().startDownload(downloadUrl); break; case R.ID.stop_btn: DownloadUtils.getInstance().stopDownload(); break; } } /** * 安装apk * @param file */ private voID installApk(file file) { Intent intent = new Intent(); intent.setAction(Intent.ACTION_VIEW); intent.addcategory("androID.intent.category.DEFAulT"); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromfile(file),"application/vnd.androID.package-archive"); startActivity(intent); androID.os.Process.killProcess(androID.os.Process.myPID()); } }
上面的自动安装是installApk这个方法,这个没必要去了解太多,都是AndroID的一个固定方法,一般网上都会有的,希望可以帮到大家!
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
您可能感兴趣的文章:android多线程断点下载-带进度条和百分比进度显示效果Android HttpURLConnection断点下载(单线程)Android原生实现多线程断点下载实例代码详解Android中的多线程断点下载Android入门:多线程断点下载详细介绍Android使用多线程实现断点下载Android实现断点下载的方法@L_502_7@android自动安装apk代码实例(不使用apk安装器安装) 总结以上是内存溢出为你收集整理的Android 断点下载和自动安装的示例代码全部内容,希望文章能够帮你解决Android 断点下载和自动安装的示例代码所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)