Android: loading data from the web in background thread with a "progress" GUI? [duplicate]
Possible Duplicate:
Download a file with Android, and showing the progress in a ProgressDialog
I want to load info from a web server into my app. Currently I'm doing it in the main thread, which I've read is very bad practice (if the request takes longer than 5 secs, the app crashes).
So instead I'd like to learn how to move this operation to a background thread. Does this involve a service somehow?
Here is a sample of the code where I make server requests:
// send data
URL url = new URL("http://www.myscript.php");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
// Get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line +开发者_Go百科 "\n");
}
wr.close();
rd.close();
String result = sb.toString();
Intent i = new Intent(searchEventActivity.this, searchResultsActivity.class);
i.putExtra("result", result);
startActivity(i);
So I'm waiting to build up a JSON string response, then I'm passing that string to a new activity. This is a timely operation, and instead of hanging the UI, I'd like to show the user a nice "Progress" bar of some sort (even one of those circles with the spinning lights is good) while this URL business is happening in a background thread.
Thanks for any help or links to tutorials.
The basic idea of the process is to create a Thread
to handle the web request, then use Handler
s and Runnable
s to manage the UI interaction.
The way that I manage this in my apps is to use a custom class that includes all of the intelligence and business rules to manage my communications. It also includes variables in the constructor to allow the UI thread to be called.
Here's an example:
public class ThreadedRequest
{
private String url;
private Handler mHandler;
private Runnable pRunnable;
private String data;
private int stausCode;
public ThreadedRequest(String newUrl, String newData)
{
url = newUrl;
data = newData;
mHandler = new Handler();
}
public void start(Runnable newRun)
{
pRunnable = newRun;
processRequest.start();
}
private Thread processRequest = new Thread()
{
public void run()
{
//Do you request here...
if (pRunnable == null || mHandler == null) return;
mHandler.post(pRunnable);
}
}
}
This would be called from your UI thread as follows:
final ThreadedRequest tReq = new ThreadedRequest(url, maybeData);
//This method would start the animation/notification that a request is happening
StartLoading();
tReq.start(new Runnable()
{
public void run()
{
//This would stop whatever the other method started and let the user know
StopLoading();
}
});
精彩评论