好的,这是使用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"); }}


