1. 권한 설정
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:usesCleartextTraffic="true">
2. build.gradle(app)
dependencies {
implementation 'com.android.volley:volley:1.2.1'
}
3. 싱글톤 클래스 생성(RequestQueue 설정)
class MySingleton constructor(context: Context) {
companion object {
@Volatile
private var INSTANCE: MySingleton? = null
fun getInstance(context: Context) =
INSTANCE ?: synchronized(this) {
INSTANCE ?: MySingleton(context).also {
INSTANCE = it
}
}
}
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)
}
}
4. 사용하기
val url = "http://www.example.com"
// Formulate the request and handle the response.
val stringRequest = StringRequest(Request.Method.GET, url,
Response.Listener<String> { response ->
// Do something with the response
},
Response.ErrorListener { error ->
// Handle error
})
val queue = MySingleton.getInstance(this.applicationContext).requestQueue
queue.add(stringRequest)
- 깃허브 주소 : https://github.com/google/volley