New Thread
and AsyncTask solutions have been explained already.
AsyncTask
should ideally be used for short operations. Normal Thread
is not preferable for Android.
Have a look at alternate solution using HandlerThread and Handler
HandlerThread
Handy class for starting a new thread that has a looper. The looper can then be used to create handler classes. Note that
start()
must still be called.
Handler:
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue. Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue.
Solution:
Create
HandlerThread
Call
start()
onHandlerThread
Create
Handler
by gettingLooper
fromHanlerThread
Embed your Network operation related code in
Runnable
objectSubmit
Runnable
task toHandler
Sample code snippet, which address NetworkOnMainThreadException
HandlerThread handlerThread = new HandlerThread("URLConnection");
handlerThread.start();
handler mainHandler = new Handler(handlerThread.getLooper());
Runnable myRunnable = new Runnable() {
@Override
public void run() {
try {
Log.d("Ravi", "Before IO call");
URL page = new URL("http://www.google.com");
StringBuffer text = new StringBuffer();
HttpURLConnection conn = (HttpURLConnection) page.openConnection();
conn.connect();
InputStreamReader in = new InputStreamReader((InputStream) conn.getContent());
BufferedReader buff = new BufferedReader(in);
String line;
while ( (line = buff.readLine()) != null) {
text.append(line + "\n");
}
Log.d("Ravi", "After IO call");
Log.d("Ravi",text.toString());
}catch( Exception err){
err.printStackTrace();
}
}
};
mainHandler.post(myRunnable);
Pros of using this approach:
- Creating new
Thread/AsyncTask
for each network operation is expensive. TheThread/AsyncTask
will be destroyed and re-created for next Network operations. But withHandler
andHandlerThread
approach, you can submit many network operations (as Runnable tasks) to singleHandlerThread
by usingHandler
.