很多APP都會有自動更新APP然后本地安裝的功能 之前一直是用AsnycTask來做的 最近發現AsyncTask被標記為過時 那么就換一種方式來寫吧
我自己是做在Dialog里面 使用okhttp進行文件下載 配合自定義View的進度條進行展示的
首先老規矩上圖
開始下載了
下載完成后自動進入安裝頁面
話不多說 我們先來定義一個用來回調的接口 分別對應成功 失敗 和進度
interface DownloadListener {
fun onSuccess()
fun onFailed(msg: String)
fun onProgress(progress: Int)
}
首先就是我們對于文件的處理
//首先是我們的下載地址 沒什么好說的就使用app本地的file文件夾就可以了
val path = getExternalFilesDir(null)!!.absolutePath+"/app.apk"
//先生成我們的文件
val file = File(path)
//這里看你需求 是否需要短線點續傳 需要的話就記錄一下當前下載長度
var currentLength = 0L
if (file.exists()){
// currentLength=file.length()//下載長度 如果你需要斷點續傳就使用這個參數并去掉刪除文件的方法
file.delete()
}
接著創建一個okhttp實例并獲取我們目標文件的總長度(大小)用來處理我們下載的百分比
private val client = OkHttpClient()
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
return if (response.isSuccessful) {
//獲取文件長度
val length = response.body?.contentLength() as Long
response.body!!.close()
length
} else {
//如果回調失敗了就返回長度為0
0
}
根據長度來判斷文件是否下載完了
val fileLength = fileLength(url)//獲取文件總長度
if (fileLength == 0L) {//如果獲取的文件長度為0則失敗
listener.onFailed("文件長度為0")
} else if (currentLength == fileLength) {//如果獲取的文件長度和下載的文件長度相等則下載完畢
listener.onSuccess()
}
接著就要開始下載文件咯
//使用OkHttp進行APK下載
//請求頭為RANGE 如果是斷點續傳就是bytes=[start,end]
val request = Request.Builder().addHeader("RANGE", "bytes=$currentLength-").url(url).build()
val response = client.newCall(request).execute()
val inputStream = response.body?.byteStream()
val saverFile = RandomAccessFile(file, "rw")
saverFile.seek(currentLength)
val b = ByteArray(1024)
var total = 0
var len = inputStream!!.read(b)
while (len != -1) {
total += len
saverFile.write(b, 0, len)
val progress = ((total + currentLength) * 100 / fileLength).toInt()
//下載的百分比回調
listener.onProgress(progress)
len = inputStream.read(b)
}
response.body?.close()
inputStream.close()
saverFile.close()
//下載完畢
listener.onSuccess()
文件下載完畢就可以進行apk的安裝了
val file=File(path)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.parse("file://$file"), "application/vnd.android.package-archive")
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//這邊使用你自己定義的FileProvider 此處就不進行講解了
val contentUri = FileProvider.getUriForFile(this, "com.xxxx.provider", file)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
} else {
intent.setDataAndType(Uri.parse("file://$file"), "application/vnd.android.package-archive")
}
startActivity(intent)
//殺掉APP
android.os.Process.killProcess(android.os.Process.myPid())
另外需要使用的權限有 都不是運行時權限
//安裝本地APK的權限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
//訪問網絡的權限
<uses-permission android:name="android.permission.INTERNET" />
好了完結散花 最后送上我封裝好的代碼
首先是接口
interface DownloadListener {
fun onSuccess()
fun onFailed(msg: String)
fun onProgress(progress: Int)
}
//然后是下載的工具類
object DownloadUtil{
private val client = OkHttpClient()
fun download(url:String,path:String,listener:DownloadListener){
thread {
val file = File(path)
var currentLength = 0L
if (file.exists()){
// currentLength=file.length()//下載長度 如果你需要斷點續傳就使用這個參數并去掉刪除的方法
file.delete()
}
val fileLength = fileLength(url)//獲取文件總長度
if (fileLength == 0L) {//如果獲取的文件長度為0則失敗
listener.onFailed("文件長度為0")
} else if (currentLength == fileLength) {//如果獲取的文件長度和下載的文件長度相等則下載完畢
listener.onSuccess()
}
//使用OkHttp進行APK下載
//請求頭為RANGE 如果是斷點續傳就是bytes=[start,end]
val request = Request.Builder().addHeader("RANGE", "bytes=$currentLength-").url(url).build()
val response = client.newCall(request).execute()
val inputStream = response.body?.byteStream()
val saverFile = RandomAccessFile(file, "rw")
saverFile.seek(currentLength)
val b = ByteArray(1024)
var total = 0
var len = inputStream!!.read(b)
while (len != -1) {
total += len
saverFile.write(b, 0, len)
val progress = ((total + currentLength) * 100 / fileLength).toInt()
//下載的百分比回調
listener.onProgress(progress)
len = inputStream.read(b)
}
response.body?.close()
inputStream.close()
saverFile.close()
//下載完畢
listener.onSuccess()
}
}
//獲取文件長度
private fun fileLength(url: String): Long {
val request = Request.Builder().url(url).build()
val response = client.newCall(request).execute()
return if (response.isSuccessful) {
val length = response.body?.contentLength() as Long
response.body!!.close()
length
} else {
0
}
}
}
接著是用來展示下載頁面的Dialog
class UpdateDialog( private val downloadUrl: String, private val path: String, private val because: String) : DialogFragment() {
//進度展示
private var mProgressTV: TextView? = null
private var mBecauseTV: TextView? = null
private var mUpdateViw: UpdateProgressView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view=inflater.inflate(R.layout.layout_update_dialog,container,false)
mProgressTV = view.findViewById(R.id.mProgressTV)
mBecauseTV = view.findViewById(R.id.mBecauseTV)
mUpdateViw = view.findViewById(R.id.mUpdateViw)
mBecauseTV?.text = because.handlerNull()
DownloadUtil.download(downloadUrl, path, object : DownloadListener {
override fun onSuccess() {
updateApp(path)
}
override fun onFailed(msg: String) {
myLog("下載失敗了")
}
override fun onProgress(progress: Int) {
myLog("下載百分比:$progress %")
mUpdateViw?.handlerPercent(progress)
requireActivity().runOnUiThread {
val p="正在升級中${progress}%"
mProgressTV?.text = p
}
}
})
return view
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setStyle(STYLE_NORMAL, R.style.CommonDialog)
}
private fun updateApp(path: String) {
MyLog.d("安裝APP")
val file = File(path)
val intent = Intent(Intent.ACTION_VIEW)
intent.setDataAndType(Uri.parse("file://$file"), "application/vnd.android.package-archive")
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
val contentUri = FileProvider.getUriForFile(requireContext(), "com.xxxx.provider", file)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
} else {
intent.setDataAndType(Uri.parse("file://$file"), "application/vnd.android.package-archive")
}
requireActivity().startActivity(intent)
//殺掉APP
android.os.Process.killProcess(android.os.Process.myPid())
}
}
dialog的頁面 這里使用的展示進度條的自定義View可以看我另外一篇文章
http://www.lxweimin.com/p/001fc038b557
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<LinearLayout
android:gravity="center_horizontal"
android:layout_width="260dp"
android:layout_height="300dp"
android:background="@drawable/bg_solid_whit_radius5dp"
android:orientation="vertical"
tools:ignore="UselessParent">
<TextView
android:id="@+id/mBecauseTV"
android:textSize="12sp"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<com.android.bowenporjectv2.weiget.UpdateProgressView
android:id="@+id/mUpdateViw"
android:layout_width="150dp"
android:layout_height="150dp"/>
<TextView
android:layout_marginHorizontal="20dp"
android:id="@+id/mProgressTV"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="20dp"
android:text="正在升級中...%"
android:textSize="12sp" />
</LinearLayout>
</LinearLayout>
dialog的樣式
<style name="CommonDialog">
<item name="android:windowCloseOnTouchOutside">true</item>
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">@android:color/transparent</item>
<item name="android:windowBackground">@android:color/transparent</item>
</style>
最后就是使用了
//下載地址
val url = "你自己app的下載地址"
//對應手機android/data/你的包名下/files/
val path = getExternalFilesDir(null)!!.absolutePath+"/app.apk"
UpdateDialog(url,path,"優化app").show(supportFragmentManager,"")