栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

使用AsyncTask传递值

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

使用AsyncTask传递值

好的,这是使用AsyncTask下载Web内容并将结果从其中返回到UI线程的整体用法的一种非常灵活的模式。

步骤1 定义一个接口,该接口将充当AsyncTask与您要获取数据的位置之间的消息总线。

public interface AsyncResponse<T> {    void onResponse(T response);}

步骤2
创建一个通用的AsyncTask扩展,它将使用任何URL并从中返回结果。您基本上已经有了这个,但是我做了一些调整。最重要的是,允许设置AsyncResponse回调接口。

public class WebDownloadTask extends AsyncTask<String, Void, String> {    private AsyncResponse<String> callback;    // Optional parameters    private String username;    private String password;    // Make a constuctor to store the parameters    public WebDownloadTask(String username, String password) {        this.username = username;        this.password = password;    }    // Don't forget to call this    public void setCallback(AsyncResponse<String> callback) {        this.callback = callback;    }    @Override    protected String doInBackground(String... params) {        String url = params[0];        return readFromFile(url);    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        if (callback != null) { callback.onResponse(s);        } else { Log.w(WebDownloadTask.class.getSimpleName(), "The response was ignored");        }    }        private String streamToString(InputStream is) throws IOException {        StringBuilder sb = new StringBuilder();        BufferedReader rd = new BufferedReader(new InputStreamReader(is));        String line;        while ((line = rd.readLine()) != null) { sb.append(line);        }        return sb.toString();    }    private String readFromFile(String myWebpage) {        String response = null;        HttpURLConnection urlConnection = null;        try { //Get the url connection URL url = new URL(myWebpage); // Unnecessary for general AsyncTask usage  urlConnection = (HttpURLConnection) url.openConnection(); InputStream inputStream = urlConnection.getInputStream(); if (inputStream != null) {     response = streamToString(inputStream);     inputStream.close();     Log.d("Final String", response); }        } catch (IOException e) { e.printStackTrace();        } finally { if (urlConnection != null) {     urlConnection.disconnect(); }        }        return response;    }}

步骤3
继续并在需要的地方使用该AsyncTask。这是一个例子。请注意,如果不使用

setCallback
,将无法获取来自AsyncTask的数据。

public class MainActivity extends Activity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        WebDownloadTask task = new WebDownloadTask("username", "password");        task.setCallback(new AsyncResponse<String>() { @Override public void onResponse(String response) {     // Handle response here. E.g. parse into a JSON object     // Then put objects into some list, then place into an adapter...      Toast.makeText(getApplicationContext(), response, Toast.LENGTH_SHORT).show(); }        });        // Use any URL, this one returns a list of 10 users in JSON        task.execute("http://jsonplaceholder.typipre.com/users");    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/609083.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号