0

我有一个从主线程调用的 AsyncTask,我希望在它完成时弹出一个对话框。除了将对话代码放在 OnPostExecute() 中之外,有没有办法可以将它放在主要活动代码中?

谢谢。

4

1 回答 1

0

您可以为此使用接口。它很简单而且很前进:1-创建一个新界面:

public interface IShowPopup {
    public void showPopup(String title, string message);
}

2 - 在您的活动中实现该接口:

... MyActivity extends Activity implements IShowPopup {
        ...
        public void showPopup(String title, String message) {
            // create a DialogAlert here.
            AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
            builder.setMessage(message);
            builder.setTitle(R.string.app_license_title);
            AlertDialog dialog = builder.create();

            // show dialog.
            dialog.show();
        }
        ...
     }

3 - 在您的任务中,您保留一个活动实例:

 ...MyTask extends AsyncTask<...> {
        private IShowPopup iShowPopup ;
        // get the interface from constructor.
        public MyTask(IShowPopup isp) {
            this.iShowPopup = isp;
        }

4 - 使用 onPostExecute 中的接口:

@Override
public void onPostExecute(??) {
    // get some title and message.
    iShowPopup.showPopup(title, message);
}

应该是这样!

于 2013-09-25T16:45:05.813 回答