我有一个由 Android Studio 3.2.1 创建的带有 ViewModel 的新 fragment 。
目标是使用 Google 提出的 Volley Singleton 发出请求 here .
问题是 Volley Singleton 的 Google Singleton 模式依赖于 ViewModel 中不直接存在的上下文。
如何从 ViewModel 获取应用程序上下文,然后由 Volley Singleton 使用?
带 Volley 的 WebsiteRestApi 单例
package com.developer.pochttp.sampledata
import android.content.Context
import android.graphics.Bitmap
import android.support.v4.util.LruCache
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.ImageLoader
import com.android.volley.toolbox.Volley
class WebsiteRestApi constructor(context: Context) {
companion object {
@Volatile
private var INSTANCE: WebsiteRestApi? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: WebsiteRestApi(context).also {
INSTANCE = it
}
}
}
val imageLoader: ImageLoader by lazy {
ImageLoader(requestQueue,
object : ImageLoader.ImageCache {
private val cache = LruCache<String, Bitmap>(20)
override fun getBitmap(url: String): Bitmap? {
return cache.get(url)
}
override fun putBitmap(url: String, bitmap: Bitmap) {
cache.put(url, bitmap)
}
})
}
val requestQueue: RequestQueue by lazy {
// applicationContext is key, it keeps you from leaking the
// Activity or BroadcastReceiver if someone passes one in.
Volley.newRequestQueue(context.applicationContext)
}
fun <T> addToRequestQueue(req: Request<T>) {
requestQueue.add(req)
}
}
View 模型
package com.developer.pochttp.ui.main
import android.arch.lifecycle.ViewModel
class MainViewModel : ViewModel() {
}
最佳答案
只需创建一个 Application 类:
public class MyApplication extends Application {
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public static Context getAppContext() {
return mInstance.getApplicationContext();
}
}
Manifest.xml文件编辑
<application
android:name=".MyApplication"
></application>
您可以为 volley 提供一个足以让 volley 运行的应用程序上下文。 所以现在
VolleySingleton.getInstance(MyApplication.getAppContext());
可以让你的截击在任何地方发挥作用。
关于android - 从 ViewModel 使用 Volley Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53479620/