从ViewModel使用Volley Singleton

时间:2018-11-26 10:56:42

标签: android mvvm android-volley

我有一个带有Android Studio 3.2.1创建的ViewModel的新片段。

目标是使用Google here提出的Volley Singleton进行请求。

问题在于,Volley Singleton的Google Singleton模式取决于上下文,该上下文不直接出现在ViewModel中。

如何从ViewModel获取应用程序上下文,然后由Volley Singleton使用该上下文?

网站RestApi Singleton with Volley

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)
    }
}

ViewModel

package com.developer.pochttp.ui.main

import android.arch.lifecycle.ViewModel

class MainViewModel : ViewModel() {


}

1 个答案:

答案 0 :(得分:0)

只需创建一个像这样的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运行的Application上下文。 所以现在

VolleySingleton.getInstance(MyApplication.getAppContext());  

可以在任何地方使您的凌空抽空发挥作用。