如何将数据从异步任务传递到调用它的活动? [英] How to pass data from an asynchronous task to an activity that called it?
问题描述
我是Android新手.我在异步任务中使用套接字,并且希望将数据传递回调用它的活动.但是我不希望异步任务处理UI.我只想传递数据. e![在此处输入图像描述] [1] xtends异步任务的类不是扩展活动的类的一部分
I am new to Android. I am using Sockets in an asynchronous task and I wish to pass data back to the activity that called it. But I do not want the asynchronous task to handle the UI. I just wish to pass data. The class that e![enter image description here][1]xtends async task is not a part of the class that extends activity
我的活动有2个按钮.单击该按钮时,将调用异步任务,并且应该对其余的活动进行相应的更改.
My activity has 2 buttons. When the button is clicked, async task is called and corresponding changes should be made to rest of the activity.
推荐答案
是的,您可以使用处理程序在AsyncTask和Activity之间进行通信,请参见以下示例,这将有所帮助,
Yes you can use handler to communicate between AsyncTask and Activity, see following example, it will help,
@Override
protected void onPostExecute(Object result) {
super.onPostExecute(result);
Message message = new Message();
Bundle bundle = new Bundle();
bundle.putString("file", pdfPath);
message.setData(bundle);
handler.sendMessage(message); // pass handler object from activity
}
将以下代码放入Activity类
put following code into Activity class
Handler handler = new android.os.Handler() {
@Override
public void handleMessage(Message msg) {
String filePath = msg.getData().getString("file"); // You can change this according to your requirement.
}
};
如果您不了解Handler类,请先阅读以下链接,它将为您提供帮助
If you dont't aware of Handler class then first read following link, it will help you
https://developer.android.com/training/multiple-线程/communicate-ui.html
这篇关于如何将数据从异步任务传递到调用它的活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!