Back to project page Stormy.
The source code is released under:
This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a co...
If you think the Android project Stormy 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 hmmelton.com.stormy; //from ww w. ja va 2 s .c o m import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.graphics.drawable.Drawable; import android.location.Address; import android.location.Geocoder; import android.location.Location; import android.location.LocationManager; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.AsyncTask; import android.os.Bundle; import android.provider.Settings; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.List; import java.util.Locale; import butterknife.ButterKnife; import butterknife.InjectView; public class MainActivity extends ActionBarActivity { public static final String TAG = MainActivity.class.getSimpleName(); private CurrentWeather mCurrentWeather; private double[] mGps = new double[2]; @InjectView(R.id.timeLabel) TextView mTimeLabel; @InjectView(R.id.temperatureLabel) TextView mTemperatureLabel; @InjectView(R.id.humidityValue) TextView mHumidityValue; @InjectView(R.id.precipValue) TextView mPrecipValue; @InjectView(R.id.summaryLabel) TextView mSummaryLabel; @InjectView(R.id.iconImageView) ImageView mIconImageView; @InjectView(R.id.refreshImageView) ImageView mRefreshImageView; @InjectView(R.id.progressBar) ProgressBar mProgressBar; @InjectView(R.id.locationLabel) TextView mLocationLabel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mProgressBar.setVisibility(View.INVISIBLE); getGps(); mRefreshImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getGps(); getForecast(mGps[0], mGps[1]); } }); getForecast(mGps[0], mGps[1]); } private void getGps() { LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) { Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location != null) { mGps[0] = location.getLatitude(); mGps[1] = location.getLongitude(); (new GetAddressTask(this)).execute(location); } else { mLocationLabel.setText(getString(R.string.no_location)); } } else { makeUserTurnOnGps(); } } private void makeUserTurnOnGps() { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.error_title)); builder.setMessage(getString(R.string.gps_error_message)); // opens Settings builder.setPositiveButton(getString(R.string.settings), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); startActivity(intent); } }); // closes the app builder.setNegativeButton(getString(R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { finish(); System.exit(0); } }); AlertDialog dialog = builder.create(); dialog.show(); } private void getForecast(double latitude, double longitude) { String apiKey = "0e70b9d7534173352a99b6b75c13533f"; String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," +longitude; if (isNetworkAvailable()) { toggleRefresh(); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(forecastUrl) .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Request request, IOException e) { runOnUiThread(new Runnable() { @Override public void run() { toggleRefresh(); } }); alertUserAboutError(); } @Override public void onResponse(Response response) throws IOException { runOnUiThread(new Runnable() { @Override public void run() { toggleRefresh(); } }); try { String jsonData = response.body().string(); if (response.isSuccessful()) { mCurrentWeather = getCurrentDetails(jsonData); runOnUiThread(new Runnable() { @Override public void run() { updateDisplay(); } }); } else { alertUserAboutError(); } } catch (IOException e) { Log.e(TAG, "Exception caught!", e); } catch (JSONException e) { Log.e(TAG, "Exception caught!", e); } } }); } else { Toast.makeText(this, getString(R.string.network_unavailable_message), Toast.LENGTH_LONG).show(); } } private void toggleRefresh() { if (mProgressBar.getVisibility() == View.INVISIBLE) { mProgressBar.setVisibility(View.VISIBLE); mRefreshImageView.setVisibility(View.INVISIBLE); } else { mProgressBar.setVisibility(View.INVISIBLE); mRefreshImageView.setVisibility(View.VISIBLE); } } private void updateDisplay() { mTemperatureLabel.setText(mCurrentWeather.getTemperature() + ""); mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be"); mHumidityValue.setText(mCurrentWeather.getHumidity() + ""); mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%"); mSummaryLabel.setText(mCurrentWeather.getSummary()); Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId()); mIconImageView.setImageDrawable(drawable); } private CurrentWeather getCurrentDetails(String jsonData) throws JSONException { JSONObject forecast = new JSONObject(jsonData); String timezone = forecast.getString("timezone"); JSONObject currently = forecast.getJSONObject("currently"); CurrentWeather currentWeather = new CurrentWeather(); currentWeather.setHumidity(currently.getDouble("humidity")); currentWeather.setTime(currently.getLong("time")); currentWeather.setIcon(currently.getString("icon")); currentWeather.setPrecipChance(currently.getDouble("precipProbability")); currentWeather.setSummary(currently.getString("summary")); currentWeather.setTemperature(currently.getDouble("temperature")); currentWeather.setTimeZone(forecast.getString("timezone")); return currentWeather; } private boolean isNetworkAvailable() { ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = manager.getActiveNetworkInfo(); boolean isAvailable = false; if (networkInfo != null && networkInfo.isConnected()) { isAvailable = true; } return isAvailable; } private void alertUserAboutError() { AlertDialogFragment dialog = new AlertDialogFragment(); dialog.show(getFragmentManager(), "error_dialog"); } private class GetAddressTask extends AsyncTask<Location, Void, String> { Context mContext; public GetAddressTask(Context context) { super(); mContext = context; } /** * Get a Geocoder instance, get the latitude and longitude * look up the address, and return it * * @params params One or more Location objects * @return A string containing the address of the current * location, or an empty string if no address can be found, * or an error message */ @Override protected String doInBackground(Location... params) { Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); // Get the current location from the input parameter list Location loc = params[0]; // Create a list to contain the result address List<Address> addresses = null; try { /* * Return 1 address. */ addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1); } catch (IOException e1) { Log.e("LocationSampleActivity", "IO Exception in getFromLocation()"); e1.printStackTrace(); return ("IO Exception trying to get address"); } catch (IllegalArgumentException e2) { // Error message to post in the log String errorString = "Illegal arguments " + Double.toString(loc.getLatitude()) + " , " + Double.toString(loc.getLongitude()) + " passed to address service"; Log.e("LocationSampleActivity", errorString); e2.printStackTrace(); return errorString; } // If the reverse geocode returned an address if (addresses != null && addresses.size() > 0) { // Get the first address Address address = addresses.get(0); /* * Format the first line of address (if available), * city, and country name. */ String addressText = String.format( "%s", // Locale is usually city address.getLocality()); // Return the text return addressText; } else { return "No address found"; } } @Override protected void onPostExecute(String addressText) { mLocationLabel.setText(addressText); } } }