The main thread is the UI thread, and you cannot do an operation in the main thread which may block the user interaction. You can solve this in two ways:
Force to do the task in the main thread like this
StrictMode.ThreadPolicy threadPolicy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(threadPolicy);
Or create a simple handler and update the main thread if you want.
Runnable runnable;
Handler newHandler;
newHandler = new Handler();
runnable = new Runnable() {
@Override
public void run() {
try {
//update UI
} catch (Exception e) {
e.printStackTrace();
}
}
};
newHandler.post(runnable);
And to stop the thread use:
newHandler.removeCallbacks(runnable);
For more information check this out: Painless threading