0

我有一个 AsyncTask 类,它连接到 Web 服务以获取某些内容,然后打印到屏幕上。
这是我的代码:

public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
   private MainActivity callerActivity;
   private String credit;
   public GetCreditAsyncTask(Context context){
        callerActivity = (MainActivity )context;
    }
   @Override
    protected String doInBackground(Object... params) { 
         .....//do something and get the credit
}
   @Override
    protected void onPostExecute(String response) {
          callerActivity.txtView.setText(credit);
   }


}

它工作得很好,但现在,我还有一个 ActivityProfileActivity
也想用来GetCreditAsyncTask获得信用并将其打印到txtView
但在开始时GetCreditAsyncTask,我callerActivityMainActivity.
问题是如何只使用一个 AsyncTask 类,以便我可以调用它并获得功劳。

4

1 回答 1

0

您可以定义两个活动都实现的接口。而不是强制转换为 MainActivity,您必须强制转换为该接口。

public interface ActivityListener {
   public void setText(String text);
}


public class MainActivity extends Activity implements ActivityListener {

...

    public void setText(String text) {
        TextView tv = findViewById(R.id.main_text);
        tv.setText(text);
    }

}


public class SecondActivity extends Activity implements ActivityListener {

...

    public void setText(String text) {
        TextView tv = findViewById(R.id.secondary_text);
        tv.setText(text);
    }

}


public class GetCreditAsyncTask extends AsyncTask<Object, Boolean, String>{
   private ActivityListener callerActivity;
   private String credit;
   public GetCreditAsyncTask(Context context){
        callerActivity = (ActivityListener) context;
    }
   @Override
    protected String doInBackground(Object... params) { 
         .....//do something and get the credit
}
   @Override
    protected void onPostExecute(String response) {
          callerActivity.setText(credit);
   }


}
于 2012-11-13T03:51:10.453 回答