Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Android.App;
- using Android.Content;
- using Android.Locations;
- using Android.OS;
- using Android.Widget;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Json;
- using System.Linq;
- using System.Net;
- using System.Threading.Tasks;
- namespace PUM_ZAD3
- {
- [Activity(Label = "PUM_ZAD3", MainLauncher = true, Icon = "@drawable/icon")]
- public class MainActivity : Activity, ILocationListener
- {
- public void OnProviderDisabled(string provider) { }
- public void OnProviderEnabled(string provider) { }
- public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
- private LocationManager _locationManager;
- private string _locationProvider;
- private Location _currentLocation;
- EditText latitude;
- EditText longitude;
- TextView location;
- private bool _found = false;
- private bool _GPSworking = false;
- protected override void OnCreate(Bundle bundle)
- {
- base.OnCreate(bundle);
- SetContentView(Resource.Layout.Main);
- location = FindViewById<TextView>(Resource.Id.locationText);
- latitude = FindViewById<EditText>(Resource.Id.latText);
- longitude = FindViewById<EditText>(Resource.Id.longText);
- Button button = FindViewById<Button>(Resource.Id.getWeatherButton);
- InitializeLocationManager();
- button.Click += AddressButton_OnClick;
- }
- protected override void OnResume()
- {
- base.OnResume();
- _GPSworking = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);
- if (_GPSworking)
- {
- InitializeLocationManager();
- _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
- }
- else showGPSDisabledAlertToUser();
- }
- protected override void OnPause()
- {
- base.OnPause();
- _locationManager.RemoveUpdates(this);
- }
- private async Task<JsonValue> FetchWeatherAsync(string url)
- {
- HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
- request.ContentType = "application/json";
- request.Method = "GET";
- using (WebResponse response = await request.GetResponseAsync())
- {
- using (Stream stream = response.GetResponseStream())
- {
- JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
- Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
- return jsonDoc;
- }
- }
- }
- public async void OnLocationChanged(Location location)
- {
- _currentLocation = location;
- if (_currentLocation == null)
- {
- Toast.MakeText(this, "Unable to determine your location. Try again in a short while.", ToastLength.Short).Show();
- }
- else
- {
- Address address = await ReverseGeocodeCurrentLocation();
- if (!_found)
- {
- latitude.Text = address.Latitude.ToString();
- longitude.Text = address.Longitude.ToString();
- Toast.MakeText(this, "Localization found.", ToastLength.Short).Show();
- _found = true;
- }
- }
- }
- async void AddressButton_OnClick(object sender, EventArgs eventArgs)
- {
- if (_currentLocation == null)
- {
- Toast.MakeText(this, "Can't determine the current address. Try again in a few minutes.", ToastLength.Short).Show();
- return;
- }
- Address address = await ReverseGeocodeCurrentLocation();
- string url = "http://api.geonames.org/findNearByWeatherJSON?" +
- "lat=" + address.Latitude.ToString().Replace(",",".") +
- "&lng=" + address.Longitude.ToString().Replace(",", ".") +
- "&username=magnusarias";
- location.Text = address.GetAddressLine(0) + ", " + address.GetAddressLine(1) + "\n" + address.GetAddressLine(2);
- JsonValue json = await FetchWeatherAsync(url);
- ParseAndDisplay(json);
- }
- async Task<Address> ReverseGeocodeCurrentLocation()
- {
- Geocoder geocoder = new Geocoder(this);
- IList<Address> addressList =
- await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
- Address address = addressList.FirstOrDefault();
- return address;
- }
- private void ParseAndDisplay(JsonValue json)
- {
- // Get the weather reporting fields from the layout resource:
- TextView temperature = FindViewById<TextView>(Resource.Id.tempText);
- TextView humidity = FindViewById<TextView>(Resource.Id.humidText);
- TextView conditions = FindViewById<TextView>(Resource.Id.condText);
- TextView barometer = FindViewById<TextView>(Resource.Id.pressureText);
- // Extract the array of name/value results for the field name "weatherObservation".
- JsonValue weatherResults = json["weatherObservation"];
- // The temperature is expressed in Celsius:
- double temp = weatherResults["temperature"];
- // Convert it to Fahrenheit:
- // temp = ((9.0 / 5.0) * temp) + 32;
- // Write the temperature (one decimal place) to the temperature TextBox:
- temperature.Text = String.Format("{0:F1}", temp) + "° C";
- // Get the percent humidity and write it to the humidity TextBox:
- double humidPercent = weatherResults["humidity"];
- humidity.Text = humidPercent.ToString() + "%";
- // Get the "clouds" and "weatherConditions" strings and
- // combine them. Ignore strings that are reported as "n/a":
- string cloudy = weatherResults["clouds"];
- if (cloudy.Equals("n/a"))
- cloudy = "";
- string cond = weatherResults["weatherCondition"];
- if (cond.Equals("n/a"))
- cond = "";
- // Write the result to the conditions TextBox:
- conditions.Text = cloudy + " " + cond;
- double pressure = weatherResults["hectoPascAltimeter"];
- barometer.Text = pressure.ToString() + "hPa";
- }
- void InitializeLocationManager()
- {
- _locationManager = (LocationManager)GetSystemService(LocationService);
- Criteria criteriaForLocationService = new Criteria
- {
- Accuracy = Accuracy.Fine
- };
- IList<string> acceptableLocationProviders =
- _locationManager.GetProviders(criteriaForLocationService, true);
- if (acceptableLocationProviders.Any())
- {
- _locationProvider = acceptableLocationProviders.First();
- }
- else
- {
- _locationProvider = string.Empty;
- }
- }
- private void showGPSDisabledAlertToUser()
- {
- var alertDialogBuilder = new AlertDialog.Builder(this);
- alertDialogBuilder.SetMessage("GPS is disabled in your device. Would you like to enable it?");
- alertDialogBuilder.SetCancelable(false);
- alertDialogBuilder.SetPositiveButton("Goto Settings Page To Enable GPS", (EventHandler<DialogClickEventArgs>) null);
- alertDialogBuilder.SetNegativeButton("Cancel", (EventHandler<DialogClickEventArgs>) null);
- var dialog = alertDialogBuilder.Create();
- dialog.Show();
- var posButton = dialog.GetButton((int)DialogButtonType.Positive);
- var negButton = dialog.GetButton((int)DialogButtonType.Negative);
- posButton.Click += (sender, args) =>
- {
- Intent callGPSSettingIntent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
- StartActivity(callGPSSettingIntent);
- };
- negButton.Click += (sender, args) =>
- {
- dialog.Cancel();
- };
- }
- }
- }
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent">
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- android:id="@+id/latSection">
- <TextView
- android:text="Latitude:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="140dp"
- android:layout_height="40dp"
- android:gravity="right"
- android:id="@+id/latLabel"
- android:layout_marginLeft="0.0dp"
- android:layout_marginRight="0.0dp" />
- <EditText
- android:layout_width="150dp"
- android:layout_height="50dp"
- android:id="@+id/latText"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_marginLeft="5dp" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- android:id="@+id/longSection">
- <TextView
- android:text="Longitude:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="140dp"
- android:layout_height="40dp"
- android:gravity="right"
- android:id="@+id/longLabel" />
- <EditText
- android:layout_width="150dp"
- android:layout_height="50dp"
- android:id="@+id/longText"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_marginLeft="5dp" />
- </LinearLayout>
- <LinearLayout
- android:orientation="vertical"
- android:layout_marginTop="28dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- android:id="@+id/getSection">
- <Button
- android:id="@+id/getWeatherButton"
- android:layout_width="300dp"
- android:layout_height="wrap_content"
- android:gravity="center_horizontal"
- android:textAppearance="?android:attr/textAppearanceLarge"
- android:text="Get Weather" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="30dp"
- android:layout_marginLeft="40dp"
- android:layout_marginRight="40dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/locSection">
- <TextView
- android:text="Location:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="120dp"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/locLabel" />
- <TextView
- android:text=""
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="60dp"
- android:gravity="left"
- android:id="@+id/locationText" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_marginLeft="40dp"
- android:layout_marginRight="40dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/tempSection">
- <TextView
- android:text="Temperature:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="120dp"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/tempLabel" />
- <TextView
- android:text=""
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/tempText" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_marginLeft="40dp"
- android:layout_marginRight="40dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/humidSection">
- <TextView
- android:text="Humidity:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="120dp"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/humidLabel" />
- <TextView
- android:text=""
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/humidText" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_marginLeft="40dp"
- android:layout_marginRight="40dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/condSection">
- <TextView
- android:text="Conditions:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="120dp"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/condLabel" />
- <TextView
- android:text=""
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="60dp"
- android:gravity="left"
- android:id="@+id/condText" />
- </LinearLayout>
- <LinearLayout
- android:orientation="horizontal"
- android:layout_marginTop="10dp"
- android:layout_marginLeft="40dp"
- android:layout_marginRight="40dp"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/pressureSection">
- <TextView
- android:text="Barometer:"
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="120dp"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/pressureLabel" />
- <TextView
- android:text=""
- android:textAppearance="?android:attr/textAppearanceMedium"
- android:layout_width="wrap_content"
- android:layout_height="30dp"
- android:gravity="left"
- android:id="@+id/pressureText" />
- </LinearLayout>
- </LinearLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement