// Keep a reference to the NetworkFragment, which owns the AsyncTask object // that is used to execute network ops. private NetworkFragment mNetworkFragment;
// Boolean telling us whether a download is in progress, so we don't trigger overlapping // downloads with consecutive button clicks. privatebooleanmDownloading=false;
/** * Implementation of headless Fragment that runs an AsyncTask to fetch data from the network. */ publicclassNetworkFragmentextendsFragment { publicstaticfinalStringTAG="NetworkFragment";
/** * Static initializer for NetworkFragment that sets the URL of the host it will be downloading * from. */ publicstatic NetworkFragment getInstance(FragmentManager fragmentManager, String url) { NetworkFragmentnetworkFragment=newNetworkFragment(); Bundleargs=newBundle(); args.putString(URL_KEY, url); networkFragment.setArguments(args); fragmentManager.beginTransaction().add(networkFragment, TAG).commit(); return networkFragment; }
/** * Cancel (and interrupt if necessary) any ongoing DownloadTask execution. */ publicvoidcancelDownload() { if (mDownloadTask != null) { mDownloadTask.cancel(true); } } ...
/** * Implementation of AsyncTask designed to fetch data from the network. */ privateclassDownloadTaskextendsAsyncTask<String, Integer, DownloadTask.Result> {
/** * Wrapper class that serves as a union of a result value and an exception. When the download * task has completed, either the result value or exception can be a non-null value. * This allows you to pass exceptions to the UI thread that were thrown during doInBackground(). */ staticclassResult { public String mResultValue; public Exception mException; publicResult(String resultValue) { mResultValue = resultValue; } publicResult(Exception exception) { mException = exception; } }
/** * Cancel background network operation if we do not have network connectivity. */ @Override protectedvoidonPreExecute() { if (mCallback != null) { NetworkInfonetworkInfo= mCallback.getActiveNetworkInfo(); if (networkInfo == null || !networkInfo.isConnected() || (networkInfo.getType() != ConnectivityManager.TYPE_WIFI && networkInfo.getType() != ConnectivityManager.TYPE_MOBILE)) { // If no connectivity, cancel task and update Callback with null data. mCallback.updateFromDownload(null); cancel(true); } } }
/** * Defines work to perform on the background thread. */ @Override protected DownloadTask.Result doInBackground(String... urls) { Resultresult=null; if (!isCancelled() && urls != null && urls.length > 0) { StringurlString= urls[0]; try { URLurl=newURL(urlString); StringresultString= downloadUrl(url); if (resultString != null) { result = newResult(resultString); } else { thrownewIOException("No response received."); } } catch(Exception e) { result = newResult(e); } } return result; }
/** * Updates the DownloadCallback with the result. */ @Override protectedvoidonPostExecute(Result result) { if (result != null && mCallback != null) { if (result.mException != null) { mCallback.updateFromDownload(result.mException.getMessage()); } elseif (result.mResultValue != null) { mCallback.updateFromDownload(result.mResultValue); } mCallback.finishDownloading(); } }
/** * Override to add special behavior for cancelled AsyncTask. */ @Override protectedvoidonCancelled(Result result) { } }
/** * Indicates that the callback handler needs to update its appearance or information based on * the result of the task. Expected to be called from the main thread. */ voidupdateFromDownload(T result);
/** * Get the device's active network status in the form of a NetworkInfo object. */ NetworkInfo getActiveNetworkInfo();
/** * Indicate to callback handler any progress update. * @param progressCode must be one of the constants defined in DownloadCallback.Progress. * @param percentComplete must be 0-100. */ voidonProgressUpdate(int progressCode, int percentComplete);
/** * Indicates that the download operation has finished. This method is called even if the * download hasn't completed successfully. */ voidfinishDownloading(); }