Reputation: 26034
I have a class annotated with @Rest
and I use its methods in another with an instance of this, annotated with @RestService
. When I call some method of the Rest client class, NetworkOnMainThreadException
error appears. I thought that AndroidAnnotations managed the threading in these cases.
Upvotes: 1
Views: 584
Reputation: 12207
AndroidAnnotations does not make the implementation to use a background thread. Actually it should not have to, since it is uncertain whether the call is already on a background thread or not, etc. But you can easily put calls to a background thread with the @Background
annotation. With the usage of that, you can simply avoid the AsyncTask
boilerplate.
Upvotes: 1
Reputation: 12382
The exception that is thrown when an application attempts to perform a networking operation on its main thread.
This is only thrown for applications targeting the Honeycomb SDK or higher. Applications targeting earlier SDK versions are allowed to do networking on their main event loop threads, but it's heavily discouraged. See the document Designing for Responsiveness.
The most effecive way to create a worker thread for longer operations is with the AsyncTask class. Simply extend AsyncTask
and implement the doInBackground()
method to perform the work. To post progress changes to the user, you can call publishProgress()
, which invokes the onProgressUpdate()
callback method. From your implementation of onProgressUpdate()
(which runs on the UI thread), you can notify the user. For example:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
// Do the long-running work in here
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
// This is called each time you call publishProgress()
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
// This is called when doInBackground() is finished
protected void onPostExecute(Long result) {
showNotification("Downloaded " + result + " bytes");
}
}
To execute this worker thread, simply create an instance and call execute():
new DownloadFilesTask().execute(url1, url2, url3);
Upvotes: 0
Reputation: 502
You are calling a RESTful web service, which is a network operation. As Android architecture says, network operation should be done on another thread than UI thread. For this you have to start another thread to do that operation, but the best practice is to use AsyncTask
Upvotes: 0