Runt
2024-09-28 1464250d6b481fb9274cc571ecbe031b71ab457c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package com.runt.open.mvi.base.model
 
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.runt.open.mvi.base.BaseActivity
import com.runt.open.mvi.base.LayoutView
import com.runt.open.mvi.retrofit.AndroidScheduler
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.schedulers.Schedulers
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
 
/**
 *
 * @author Runt(qingingrunt2010@qq.com)
 * @purpose
 * @date 6/1/24
 */
open abstract class BaseViewModel : ViewModel(){
    var TAG = "";
 
    protected var mActivity : BaseActivity<LayoutView<BaseViewModel> , BaseViewModel>? = null
    var verifyResult = MutableLiveData<Int>()
 
    open fun onCreate(activity : BaseActivity<LayoutView<BaseViewModel> , BaseViewModel>) {
        mActivity = activity
        TAG = javaClass.simpleName;
    }
 
    fun getActivity(): ComponentActivity {
        return mActivity!!;
    }
 
    /**
     * 获取用户信息
     */
    /*fun getUserBean() {
        httpObserverOn(commonApi.getUserBean() , object : HttpObserver<UserBean?>() {
            protected fun onSuccess(data : UserBean?) {
                UserBean.setUser(data)
            }
        })
    }*/
 
    /**
     * 随机字符串
     * @param phone
     * @param time
     * @return
     */
    fun randomString(phone : String , time : String) : String {
        val p = Math.round(phone.length / 6.0).toInt()
        val t = time.length / 6
        val list : MutableList<String> = ArrayList()
        for (i in 0 .. 5) {
            var str = ""
            str = if (i * p > phone.length) {
                phone.substring((i - 1) * p)
            } else if ((i + 1) * p > phone.length) {
                phone.substring(i * p)
            } else {
                phone.substring(i * p , (i + 1) * p)
            }
            val num = (str.toInt() * time.toLong()).toString() + ""
            list.add(num)
        } //return sb.toString();
        return plusSingle2(list)
    }
 
    private fun plusSingle2(list : List<String>) : String {
        val sb = StringBuilder()
        for (i in list.indices) {
            sb.append(list[i].substring(if (list[i].length - 2 < 0) 0 else list[i].length - 2))
        }
        return sb.toString()
    }
 
 
    private fun downloadApk(url : String) {
        val request : Request = Request.Builder().url(url).build()
        val client = OkHttpClient()
        client.newCall(request).enqueue(object : Callback {
            override fun onResponse(call : okhttp3.Call , response : Response) {
                val code : Int = response.code
                Log.d("downloadFile" , "code:$code")
                if (code != 200) {
                    mActivity!!.showToast("下载失败$code")
                    return
                }
                var fos : FileOutputStream? = null
                var input : InputStream? = null
                var file : File? = null
                val buf = ByteArray(2048)
                var len = 0
                try {
                    Log.d("downloadFile" , "下载文件:$url")
                    input = response.body!!.byteStream()
                    val total : Long = response.body!!.contentLength()
                    Log.d("downloadFile" , "total:$total")
                    file = File(mActivity!!.getExternalFilesDir(null)!!.getAbsolutePath() + "/")
                    if (! file !!.exists()) {
                        file.mkdirs()
                    }
                    file = File(file.path + "/" + url.substring(url.lastIndexOf("/")))
                    file.createNewFile()
                    fos = FileOutputStream(file)
                    var sum : Long = 0
                    while (input.read(buf).also { len = it } != - 1) {
                        fos.write(buf , 0 , len)
                        sum += len.toLong()
                        val progress = sum * 1.0f / total * 100 // 下载中
                        Log.d("downloadFile" , "下载进度:$progress")
                    }
                    Log.d("downloadFile" , file.path) // 下载完成
                    val finalFile : File = file
                    mActivity!!.runOnUiThread {
                        /*mActivity!!.showDialog("安装" , "新版安装包下载完成" , "安装" , "取消" , object : ResPonse() {
                            fun doSuccess(obj : Any?) {
                                openAPK(finalFile)
                            }
                        })*/
                    }
                } catch (e : Exception) {
                    Log.d("downloadFileException" , e.toString())
                    Log.d("downloadFileException" , "Url:\${call.request().url}")
                    mActivity!!.showToast("下载失败$e")
                    file !!.delete()
                    call.cancel()
                } finally {
                    fos !!.flush()
                    input !!.close()
                    fos.close()
                }
            }
 
            override fun onFailure(call : okhttp3.Call , e : IOException) {
                mActivity!!.showToast("下载失败$e")
            }
 
        })
    }
 
    /**
     * 打开apk文件
     *
     * @param file
     */
    private fun openAPK(file : File) {
        val intent = Intent()
        intent.setAction(Intent.ACTION_VIEW)
        var photoURI : Uri? = null
        photoURI = if (Build.VERSION.SDK_INT >= 24) { //判读版本是否在7.0以上
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            FileProvider.getUriForFile(mActivity!! , mActivity!!.getApplicationContext().getPackageName() + ".fileprovider" , file) //添加这一句表示对目标应用临时授权该Uri所代表的文件
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            Uri.fromFile(file)
        }
        intent.setDataAndType(photoURI , "application/vnd.android.package-archive")
        mActivity!!.startActivity(intent)
    }
 
    /**
     * 网络请求观察
     * @param observable
     * @param <T>
     * @return
    </T> */
    fun <T> httpObserverOn(observable : Observable<T> , observer : Observer<T>) {
        observable.subscribeOn(Schedulers.io()) //指定网络请求在io后台线程中进行
            .observeOn(AndroidScheduler.mainThread()).subscribe(observer)
    }
 
 
    /**
     * 网络请求观察(加载框)
     * @param observable
     * @param <T>
     * @return
    </T> */
    fun <T> httpObserverOnLoading(observable : Observable<T> , observer : Observer<T>) {
        observable.subscribeOn(Schedulers.io()) //指定网络请求在io后台线程中进行
            .doOnSubscribe { disposable ->
                //mActivity.showLoadingDialog("")
            }
            .observeOn(AndroidScheduler.mainThread()).doOnError { throwable ->
                //mActivity.dissmissLoadingDialog()
                Log.e("ViewModel" , hashCode().toString() + " httpObserverOnLoading " + throwable)
            }.doOnComplete {
                //mActivity.dissmissLoadingDialog()
            }.subscribe(observer)
    }
 
}