I had the following code, which was being called in a class which was registered to receive periodic (1 per second) broadcasts:
public void onReceive(Context c, Intent i) {
Log.d("NET", "Polling server...");
try {
Request.getChanges();
} catch (Exception e) {
Log.w("NET", "Error polling server: " + e.toString());
}
}
However, since this code was being fired off as a BroadcastReceiver, and thus getting run in the UI thread, I was getting:
Error polling server: android.os.NetworkOnMainThreadException
So I decided to try it in an AsyncTask instead:
public void onReceive(Context c, Intent i) {
class Task extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... arg0) {
Log.d("NET", "Polling server...");
try {
Request.getChanges();
} catch (Exception e) {
Log.w("NET", "Error polling server: " + e.toString());
}
return null;
}
}
new Task().execute();
}
However, when I do this, I get no output whatsoever. Any idea what the issue is here? Thanks!
Seems you hit the same wall than me a few weeks ago. I already had one AsyncTask
running perfectly, I copied the same structure for another one, tried to start it - no result. I was going already mad with it, when I reached this.
Resuming, all you have to do is:
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.HONEYCOMB_MR1)
new Task().execute();
else
new Task().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);