我正在使用带有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!}
答案 0 :(得分:3)
您可以使用这个特定客户端实现一个单独的帮助程序类,该类保留一个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();