在另一个类中执行异步任务后刷新微调器/视图

时间:2013-03-18 08:36:41

标签: android asynchronous

我的应用程序在主要活动上有一个微调器,内容是从sqlite加载的。我的应用程序确实提供了一个下载选项,供用户从服务器下载最新数据。异步下载任务在另一个类中。

所以我的问题是如何在下载过程完成后刷新main的活动微调器?

1 个答案:

答案 0 :(得分:1)

试试这样。

1)创建一个回调接口

 public interface DownloadCompleted {
        // Define your Data type to which you want to store data after AsycTask completion
        public void onTaskComplete(String result);
    }

2)AsycTask

 public class UploadAsyncTask extends
            AsyncTask<String, Void, String> {
        private ProgressDialog Dialog;
        String response = "";
        Activity _context;
        private DownloadCompleted callback;

        public UploadAsyncTask (Activity _context) {
            this._context = _context;
            this.callback = (DownloadCompleted ) _context;
        }

        @Override
        protected void onPreExecute() {
            Dialog = new ProgressDialog(_context);
            Dialog.setMessage("Loading...");
            Dialog.show();

        }

        @Override
        protected String doInBackground(String... urls) {
            try {
                String url= urls[0];
                //Do your operation
            } catch (Exception e) {
            }
            return response ;

        }

        @Override
        protected void onPostExecute(String result) {
            Dialog.dismiss();
            callback.onTaskComplete(result);

        }

    }

3)在您的调用活动

中实现界面
public class YourActivity extends Activity implements DownloadCompleted {   

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        new UploadAsyncTask (this).execute(YOUR URL String);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.rss_reader, menu);
        return true;
    }

    @Override
    public void onTaskComplete(String result) {
        // Refresh your view here
                // use result data as after completion AsycTask
    }

}

如需更多帮助和源代码,请浏览以下链接。

http://amitandroid.blogspot.in/2013/02/android-rssfeed-with-async-task-example.html