1

我需要连接到 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 给了我这个错误:“Task 类型中的方法 setOnDoneListener(Task.OnDoneListener) 不适用于参数 (new Runnable(){})”

我怎样才能解决这个问题?

谢谢!

4

1 回答 1

1

您通过在 Annoyomous 类中的 Thread 更改了上下文,this现在是您的 annonomous 类而不是外部类。

试试这个(双关语):

 task.setOnPreExecuteListener(YourOuterClass.this);
 task.setOnDoneListener(YourOuterClass.this);

IE

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
     }

}
于 2012-12-28T11:28:14.953 回答