您始终可以扩展AsyncFacebookRunner
类并覆盖该request
方法。
像这样的东西:
public class CancelableAsyncFacebookRunner extends AsyncFacebookRunner {
private Thread requestThread;
public AsyncFacebookRunner(Facebook fb) {
super(fb);
}
@Override
public void request(final String graphPath,
final Bundle parameters,
final String httpMethod,
final RequestListener listener,
final Object state) {
this.requestThread = new Thread() {
@Override
public void run() {
try {
String resp = fb.request(graphPath, parameters, httpMethod);
listener.onComplete(resp, state);
} catch (FileNotFoundException e) {
listener.onFileNotFoundException(e, state);
} catch (MalformedURLException e) {
listener.onMalformedURLException(e, state);
} catch (IOException e) {
listener.onIOException(e, state);
}
}
};
}
public void cancel() {
this.requestThread.interrupt();
}
}
它尚未经过测试,但应该给你一个大致的想法。
编辑
现在我想了想,这没什么意义,因为您想使用AsyncFacebookRunner
发出多个请求,而cancel
只会取消最后一个请求。
我建议返回线程,然后能够在其他地方中断它,但是您不能像这样更改方法的签名,并且创建新方法将无法使用类request
中定义的其他方法AsyncFacebookRunner
。
相反,您可以执行以下操作:
public class CancelableAsyncFacebookRunner extends AsyncFacebookRunner {
private Hashtable<String, Thread> requestThreads;
public AsyncFacebookRunner(Facebook fb) {
super(fb);
this.requestThreads = new Hashtable<String, Thread>();
}
@Override
public void request(final String id,
final String graphPath,
final Bundle parameters,
final String httpMethod,
final RequestListener listener,
final Object state) {
Thread thread = new Thread() {
@Override
public void run() {
try {
String resp = fb.request(graphPath, parameters, httpMethod);
requestThreads.remove(id);
listener.onComplete(resp, state);
} catch (FileNotFoundException e) {
requestThreads.remove(id);
listener.onFileNotFoundException(e, state);
} catch (MalformedURLException e) {
requestThreads.remove(id);
listener.onMalformedURLException(e, state);
} catch (IOException e) {
requestThreads.remove(id);
listener.onIOException(e, state);
}
}
});
this.requestThreads.put(id, thread);
thread.start();
}
public void cancel(String id) {
if (this.requestThreads.containsKey(id) {
this.requestThreads.get(id).interrupt();
}
}
}
您需要以某种方式为请求生成一个 id,可以很简单,例如:
String.valueOf(System.currentTimeMillis());