3

I want to cancel AsyncTask when internet Connection is lost and show a Toast to the user, I have gone through many similar questions, but I don't know where to register the Receiver and cancel the AsyncTask.

private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {

    @Override

    public void onReceive(Context context, Intent intent) {

        boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

        String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);

                    boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
        NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);

        NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);



    }

};
  • The following might provide some assistance in this. You've got the handling of the receiver down all you need is to interrupt the AsyncTask when it happens. http://stackoverflow.com/questions/4748964/android-cancel-asynctask-forcefully – aminner Nov 10 '15 at 18:29
  • @aminner So I should Register the broadcast in the main activity and add if(noConnectivity ){ asyncTask().cancel()} to the BroadcastReceiver method – Divine Asiedu Nov 10 '15 at 18:38
  • Yes, and then you may have to add the isCancelled() in your async function per the accepted response on the response I posted. – aminner Nov 10 '15 at 18:51

0 Answers0