我需要连接到Facebook,所以我在使用网络时使用Tread。但我有一个问题:
Thread t = new Thread(new Runnable() {
@Override
public void run() {
FacebookConnectTask task = new FacebookConnectTask("facebookId", "token", "email", facebookGender,0, 0);
task.setOnPreExecuteListener(this);
task.setOnDoneListener(this);
task.execute();
}
});
t.start();
}
我无法做到
task.setOnPreExecuteListener(this);
task.setOnDoneListener(this);
eclipse给了我这个错误:“任务类型中的方法setOnDoneListener(Task.OnDoneListener)不适用于参数(new Runnable(){})”
我该如何解决这个问题?
谢谢!
答案 0 :(得分:1)
你已经通过在一个Annoyomous类中的一个Thread中改变了上下文,this
现在是你的自治类,而不是外部类。
试试这个(双关语):
task.setOnPreExecuteListener(YourOuterClass.this);
task.setOnDoneListener(YourOuterClass.this);
即
public class YourClass implements OnDoneListener {
public doFacebook(){
new Thread(new Runnable(){
@Override
public void run(){
task.setOnDoneListener(YourClass.this);
}
}.start();
}
@Override
public void onDone(){
}
}
或者将你的Threaded课程拉出来:
public class DoSomething implements Runnable {
private final OnDoneListener listener;
public DoSomething(OnDoneListener listener){
this.listener = listener;
}
@Override
public void run(){
FacebookConnectTask task = ... ;
task.setOnDoneListener(listener);
}
}
public class YourActivity extends Activity implements OnDoneListener {
public void onCreate(Bundle b){
new Thread(new DoSomething(this)).start();
}
@Override
public void onDone(){
// Tada
}
}
如果你想要更酷,那么另一步是创建自己的界面并将所有Facebook内容保存在可运行的类中:
public class DoSomething implements Runnable, OnDoneListener {
public interface OnFacebookFinished {
void onFacebookFinished();
}
private final OnFacebookFinished listener;
public DoSomething(OnFacebookFinished listener){
this.listener = listener;
}
@Override
public void run(){
FacebookConnectTask task = ... ;
task.setOnDoneListener(this);
}
@Override
public void onDone(){
if(listener != null){
listener.onFacebookFinished();
}
}
}
public class YourActivity extends Activity implements OnFacebookFinished {
@Override
public void onCreate(Bundle b){
new Thread(new DoSomething(this)).start();
}
@Override
public void onFacebookFinished(){
// Tada
}
}