0
When I perform a task (which usually requires a AsyncTask
) in the BroadcastReceiver
, he accuses me of error:
erro: android.os.NetworkOnMainThreadException
I saw that it is not a good practice a AsyncTask
within a BroadcastReceiver
.
Then the most appropriate would be a Service
? Or it’s not about the mistake !?
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.i("lgg", "onReceive " + new Date());
StringBuilder content = new StringBuilder();
try {
URL url = new URL("site.com");
URLConnection urlConnection = url.openConnection();
urlConnection.setConnectTimeout(5000);
urlConnection.setReadTimeout(5000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
content.append(line + "\n");
}
bufferedReader.close();
} catch (Exception e) {
e.printStackTrace();
Log.i("lgg", "erro: " + e);
}
Log.i("lgg", "recebido: " + content);
}
But ramaral, I’ve already tested the solution of ignoring, and the
AsyncTask
is not good practice.– rbz
A Broadcastreceiver should not be used to perform long tasks. See this reply, You can use Broadcastreceiver to launch a service that runs the time consuming operation.
– ramaral
you cannot run internet connection on Mainthread
– Weslley Barbosa