您好,登錄后才能下訂單哦!
今天說一下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,0,bytes.length)) != -1) { raf.seek(totalNum); raf.write(bytes,0,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的一個固定方法,一般網上都會有的,希望可以幫到大家!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。