How to deal with internet connection?

My application downloads data from the Internet and shows it to the user. To prevent application crashes caused by the lack of an Internet connection, I used a function that checks if it is there before downloading. I do not know how to handle cases when the connection crashes when loading a download (in AsyncTask). Catch Exepctions inputs do not work in my case :( If you have any ideas or links to tutorials, please share it. Thanks in advance

+4
source share
2 answers

Hope this helps. No matter what activity you perform, the download should create a BroadcastReceiver that can handle connection status notifications. You will then be notified that the connection has dropped and can handle it more elegantly ... for example, waiting for a notification about the return of connections and a restart of the download:

 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { boolean missingConnection = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false); String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON); // do whatever you need to based on current network state } 

This page also has good info: http://thiranjith.com/2011/03/31/how-to-monitor-network-connectivity-in-android/

+2
source

You can periodically check that connections occur outside of AsyncTask or in another thread. Then, if the connection drops, you can cancel AsyncTask by calling cancel() .

0
source

All Articles