Back to project page Weather.
The source code is released under:
Apache License
If you think the Android project Weather listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.
package com.volitic.weather; /*from w w w .j a va2 s.c o m*/ import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.preference.PreferenceManager; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.Charset; public class Network { Downloader receiver; Context context; public interface Downloader { public void downloadFailed(); public void downloadSucceeded(InputStream result); } Network( Downloader receiver, Context context ){ this.context = context; this.receiver = receiver; } public void download( String url ){ if( connectionIsValid() ){ new DownloadTask().execute(url); } else { receiver.downloadFailed(); } } public boolean connectionIsValid() { ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = connMgr.getActiveNetworkInfo(); if ((networkInfo != null && networkInfo.isConnected()) && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI || useMobile())) { return true; } return false; } private boolean useMobile(){ SharedPreferences shared_prefs = PreferenceManager.getDefaultSharedPreferences(context); return shared_prefs.getBoolean("allow_mobile_data", false); } private class DownloadTask extends AsyncTask<String, Void, InputStream> { @Override protected InputStream doInBackground(String... urls) { try { // parameter comes from the execute() call. params[0] is the url. return downloadData(urls[0]); } catch (IOException e) { return null; } } // onPostExecute displays the results of the AsyncTask. @Override protected void onPostExecute(InputStream result) { if(result == null ){ receiver.downloadFailed(); } else { receiver.downloadSucceeded(result); } } } // Given a URL, establishes an HttpUrlConnection and retrieves // the web page content as an InputStream. private InputStream downloadData(String url_string) throws IOException { URL url = new URL(url_string); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); int response = conn.getResponseCode(); if(response == 200 ){ return conn.getInputStream(); } else { return new ByteArrayInputStream(Charset.forName("UTF-8").encode( "<?xml version=\"1.0\" encoding=\"UTF-8\"?><error><response_code>" + response + "</response_code></error>" ).array()); } } }