我想创建一个以asynctask开头的单例连接。我如何getInstance并知道它何时完成连接(连接或超时)。 这是一个异步的回调接口,单例类需要执行它并存储连接。
过来this,真的不知道该怎么做。
public class ConnectAsync extends AsyncTask<String, String, Connection> {
private ConnectionCallback callback;
private Connection connection;
public ConnectAsync(ConnectionCallback callback) {
this.callback = callback;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Connection doInBackground(String... params) {
ConnectionFactory factory = new ConnectionFactory();
factory.setHost(params[0]);
factory.setUsername(params[1]);
factory.setPassword(params[2]);
factory.setConnectionTimeout(5000);
//factory.setAutomaticRecoveryEnabled(true);
//factory.setNetworkRecoveryInterval(5000);
try {
connection = factory.newConnection();
} catch (IOException e) {
LogUtil.e("Connection", null, "Connection timeout");
return null;
}
return connection;
}
@Override
protected void onPostExecute(Connection result) {
super.onPostExecute(result);
if (callback != null)
callback.onConnect(result);
}
public interface ConnectionCallback {
public void onConnect(Connection result);
}
}
来自服务
deviceWorker.connect(new ConnectionCallback() {
@Override
public void onConnect(Connection result) {
if (result != null && result.isOpen()) {
LogUtil.hecsLog(TAG, "DeviceWokers fully operational");
}
}
});