代码之家  ›  专栏  ›  技术社区  ›  Blazej SLEBODA

使用ViewModel中的单打截击

  •  0
  • Blazej SLEBODA  · 技术社区  · 6 年前

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

    目标是使用Google提出的截击Singleton请求 here .

    问题是Google单例模式对于截击单例依赖于一个ViewModel中不直接存在的上下文。

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

    网球场单杆截击

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

    视图模型

    package com.developer.pochttp.ui.main
    
    import android.arch.lifecycle.ViewModel
    
    class MainViewModel : ViewModel() {
    
    
    }
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   Jatin Sahgal    6 年前

    只需将应用程序类设置为:

    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());  
    

    可以让你的截击在任何地方发挥作用。