[英]How to create Singleton OkHtpp Class and handle previous requests
我正在使用帶有android的Google Autocomplete Places API,我正在嘗試做的是:
這就是為什么我需要一個單例實例,我試過這個:
public class OkHttpSingleton extends OkHttpClient {
private static OkHttpClient client = new OkHttpClient();
public static OkHttpClient getInstance() {
return client;
}
public OkHttpSingleton() {}
public void CloseConnections(){
client.dispatcher().cancelAll();
}
public List<PlacePredictions> getPredictions(){
//// TODO: 26/09/2017 do the request!
return null;
}
}
但我不確定這是否是正確的方法,因為在doc中它表示dispatcher().cancelAll()
方法取消所有請求但是我知道這樣做是錯誤的! 我更關心的是如何創建單身,然后是其他人。
主要活動:
Address.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
if(s.length() > 3){
_Address = Address.getText().toString();
new AsyncTask<Void, Void, String>() {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
try { // request...
}else{Clear the RecyclerView!}
您可以使用這個特定客戶端實現一個單獨的幫助程序類,該類保留一個OkHttpClient
並覆蓋所有自定義功能:
public class OkHttpSingleton {
private static OkHttpSingleton singletonInstance;
// No need to be static; OkHttpSingleton is unique so is this.
private OkHttpClient client;
// Private so that this cannot be instantiated.
private OkHttpSingleton() {
client = new OkHttpClient.Builder()
.retryOnConnectionFailure(true)
.build();
}
public static OkHttpSingleton getInstance() {
if (singletonInstance == null) {
singletonInstance = new OkHttpSingleton();
}
return singletonInstance;
}
// In case you just need the unique OkHttpClient instance.
public OkHttpClient getClient() {
return client;
}
public void closeConnections() {
client.dispatcher().cancelAll();
}
public List<PlacePredictions> getPredictions(){
// TODO: 26/09/2017 do the request!
return null;
}
}
使用示例:
OkHttpSingleton localSingleton = OkHttpSingleton.getInstance();
...
localSingleton.closeConnections();
...
OkHttpClient localClient = localSingleton.getClient();
// or
OkHttpClient localClient = OkHttpSingleton.getInstance().getClient();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.