Advertisement
MagnusArias

PUM | Zad 3.1

May 4th, 2017
330
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 15.55 KB | None | 0 0
  1. using Android.App;
  2. using Android.Content;
  3. using Android.Locations;
  4. using Android.OS;
  5. using Android.Widget;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.IO;
  9. using System.Json;
  10. using System.Linq;
  11. using System.Net;
  12. using System.Threading.Tasks;
  13.  
  14. namespace PUM_ZAD3
  15. {
  16.     [Activity(Label = "PUM_ZAD3", MainLauncher = true, Icon = "@drawable/icon")]
  17.     public class MainActivity : Activity, ILocationListener
  18.     {
  19.        
  20.         public void OnProviderDisabled(string provider) { }
  21.         public void OnProviderEnabled(string provider) { }
  22.         public void OnStatusChanged(string provider, Availability status, Bundle extras) { }
  23.         private LocationManager _locationManager;
  24.  
  25.         private string _locationProvider;
  26.         private Location _currentLocation;
  27.         EditText latitude;
  28.         EditText longitude;
  29.         TextView location;
  30.         private bool _found = false;
  31.         private bool _GPSworking = false;
  32.  
  33.         protected override void OnCreate(Bundle bundle)
  34.         {
  35.             base.OnCreate(bundle);
  36.             SetContentView(Resource.Layout.Main);
  37.  
  38.             location = FindViewById<TextView>(Resource.Id.locationText);
  39.             latitude = FindViewById<EditText>(Resource.Id.latText);
  40.             longitude = FindViewById<EditText>(Resource.Id.longText);
  41.             Button button = FindViewById<Button>(Resource.Id.getWeatherButton);
  42.  
  43.             InitializeLocationManager();
  44.             button.Click += AddressButton_OnClick;
  45.         }
  46.  
  47.         protected override void OnResume()
  48.         {
  49.             base.OnResume();
  50.             _GPSworking = _locationManager.IsProviderEnabled(LocationManager.GpsProvider);
  51.             if (_GPSworking)
  52.             {
  53.                 InitializeLocationManager();
  54.                 _locationManager.RequestLocationUpdates(_locationProvider, 0, 0, this);
  55.             }
  56.             else showGPSDisabledAlertToUser();
  57.         }
  58.  
  59.         protected override void OnPause()
  60.         {
  61.             base.OnPause();
  62.             _locationManager.RemoveUpdates(this);
  63.         }
  64.  
  65.         private async Task<JsonValue> FetchWeatherAsync(string url)
  66.         {
  67.             HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
  68.             request.ContentType = "application/json";
  69.             request.Method = "GET";
  70.  
  71.             using (WebResponse response = await request.GetResponseAsync())
  72.             {
  73.                 using (Stream stream = response.GetResponseStream())
  74.                 {
  75.                     JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
  76.                     Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
  77.  
  78.                     return jsonDoc;
  79.                 }
  80.             }
  81.         }
  82.  
  83.         public async void OnLocationChanged(Location location)
  84.         {
  85.             _currentLocation = location;
  86.             if (_currentLocation == null)
  87.             {
  88.                Toast.MakeText(this, "Unable to determine your location. Try again in a short while.", ToastLength.Short).Show();
  89.             }
  90.             else
  91.             {
  92.                 Address address = await ReverseGeocodeCurrentLocation();
  93.  
  94.                 if (!_found)
  95.                 {
  96.                     latitude.Text = address.Latitude.ToString();
  97.                     longitude.Text = address.Longitude.ToString();
  98.                     Toast.MakeText(this, "Localization found.", ToastLength.Short).Show();
  99.                     _found = true;
  100.                 }
  101.             }
  102.         }
  103.  
  104.         async void AddressButton_OnClick(object sender, EventArgs eventArgs)
  105.         {
  106.             if (_currentLocation == null)
  107.             {
  108.                 Toast.MakeText(this, "Can't determine the current address. Try again in a few minutes.", ToastLength.Short).Show();
  109.                 return;
  110.             }
  111.  
  112.             Address address = await ReverseGeocodeCurrentLocation();
  113.             string url = "http://api.geonames.org/findNearByWeatherJSON?" +
  114.             "lat=" + address.Latitude.ToString().Replace(",",".") +
  115.             "&lng=" + address.Longitude.ToString().Replace(",", ".") +
  116.             "&username=magnusarias";
  117.  
  118.             location.Text = address.GetAddressLine(0) + ", " + address.GetAddressLine(1) + "\n" + address.GetAddressLine(2);
  119.             JsonValue json = await FetchWeatherAsync(url);
  120.             ParseAndDisplay(json);
  121.         }
  122.  
  123.         async Task<Address> ReverseGeocodeCurrentLocation()
  124.         {
  125.             Geocoder geocoder = new Geocoder(this);
  126.             IList<Address> addressList =
  127.                 await geocoder.GetFromLocationAsync(_currentLocation.Latitude, _currentLocation.Longitude, 10);
  128.  
  129.             Address address = addressList.FirstOrDefault();
  130.  
  131.             return address;
  132.         }
  133.  
  134.      
  135.         private void ParseAndDisplay(JsonValue json)
  136.         {
  137.             // Get the weather reporting fields from the layout resource:
  138.            
  139.             TextView temperature = FindViewById<TextView>(Resource.Id.tempText);
  140.             TextView humidity = FindViewById<TextView>(Resource.Id.humidText);
  141.             TextView conditions = FindViewById<TextView>(Resource.Id.condText);
  142.             TextView barometer = FindViewById<TextView>(Resource.Id.pressureText);
  143.  
  144.             // Extract the array of name/value results for the field name "weatherObservation".
  145.             JsonValue weatherResults = json["weatherObservation"];
  146.  
  147.             // The temperature is expressed in Celsius:
  148.             double temp = weatherResults["temperature"];
  149.             // Convert it to Fahrenheit:
  150.             // temp = ((9.0 / 5.0) * temp) + 32;
  151.             // Write the temperature (one decimal place) to the temperature TextBox:
  152.             temperature.Text = String.Format("{0:F1}", temp) + "° C";
  153.  
  154.             // Get the percent humidity and write it to the humidity TextBox:
  155.             double humidPercent = weatherResults["humidity"];
  156.             humidity.Text = humidPercent.ToString() + "%";
  157.  
  158.             // Get the "clouds" and "weatherConditions" strings and
  159.             // combine them. Ignore strings that are reported as "n/a":
  160.             string cloudy = weatherResults["clouds"];
  161.             if (cloudy.Equals("n/a"))
  162.                 cloudy = "";
  163.             string cond = weatherResults["weatherCondition"];
  164.             if (cond.Equals("n/a"))
  165.                 cond = "";
  166.  
  167.             // Write the result to the conditions TextBox:
  168.             conditions.Text = cloudy + " " + cond;
  169.  
  170.             double pressure = weatherResults["hectoPascAltimeter"];
  171.             barometer.Text = pressure.ToString() + "hPa";
  172.         }
  173.  
  174.         void InitializeLocationManager()
  175.         {
  176.             _locationManager = (LocationManager)GetSystemService(LocationService);
  177.             Criteria criteriaForLocationService = new Criteria
  178.             {
  179.                 Accuracy = Accuracy.Fine
  180.             };
  181.             IList<string> acceptableLocationProviders =
  182.             _locationManager.GetProviders(criteriaForLocationService, true);
  183.  
  184.             if (acceptableLocationProviders.Any())
  185.             {
  186.                 _locationProvider = acceptableLocationProviders.First();
  187.             }
  188.             else
  189.             {
  190.                 _locationProvider = string.Empty;
  191.             }
  192.         }
  193.  
  194.         private void showGPSDisabledAlertToUser()
  195.         {
  196.             var alertDialogBuilder = new AlertDialog.Builder(this);
  197.  
  198.             alertDialogBuilder.SetMessage("GPS is disabled in your device. Would you like to enable it?");
  199.             alertDialogBuilder.SetCancelable(false);
  200.             alertDialogBuilder.SetPositiveButton("Goto Settings Page To Enable GPS", (EventHandler<DialogClickEventArgs>) null);
  201.             alertDialogBuilder.SetNegativeButton("Cancel", (EventHandler<DialogClickEventArgs>) null);
  202.             var dialog = alertDialogBuilder.Create();
  203.             dialog.Show();
  204.  
  205.             var posButton = dialog.GetButton((int)DialogButtonType.Positive);
  206.             var negButton = dialog.GetButton((int)DialogButtonType.Negative);
  207.  
  208.             posButton.Click += (sender, args) =>
  209.             {
  210.                 Intent callGPSSettingIntent = new Intent(Android.Provider.Settings.ActionLocationSourceSettings);
  211.                 StartActivity(callGPSSettingIntent);
  212.             };
  213.             negButton.Click += (sender, args) =>
  214.             {
  215.                 dialog.Cancel();
  216.             };
  217.  
  218.         }
  219.     }
  220. }
  221.  
  222.  
  223.  
  224. <?xml version="1.0" encoding="utf-8"?>
  225. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  226.     android:orientation="vertical"
  227.     android:layout_width="fill_parent"
  228.     android:layout_height="fill_parent">
  229.     <LinearLayout
  230.         android:orientation="horizontal"
  231.         android:layout_marginTop="10dp"
  232.         android:layout_width="match_parent"
  233.         android:layout_height="wrap_content"
  234.         android:gravity="center_horizontal"
  235.         android:id="@+id/latSection">
  236.         <TextView
  237.             android:text="Latitude:"
  238.             android:textAppearance="?android:attr/textAppearanceMedium"
  239.             android:layout_width="140dp"
  240.             android:layout_height="40dp"
  241.             android:gravity="right"
  242.             android:id="@+id/latLabel"
  243.             android:layout_marginLeft="0.0dp"
  244.             android:layout_marginRight="0.0dp" />
  245.         <EditText
  246.             android:layout_width="150dp"
  247.             android:layout_height="50dp"
  248.             android:id="@+id/latText"
  249.             android:textAppearance="?android:attr/textAppearanceMedium"
  250.             android:layout_marginLeft="5dp" />
  251.     </LinearLayout>
  252.     <LinearLayout
  253.         android:orientation="horizontal"
  254.         android:layout_marginTop="10dp"
  255.         android:layout_width="match_parent"
  256.         android:layout_height="wrap_content"
  257.         android:gravity="center_horizontal"
  258.         android:id="@+id/longSection">
  259.         <TextView
  260.             android:text="Longitude:"
  261.             android:textAppearance="?android:attr/textAppearanceMedium"
  262.             android:layout_width="140dp"
  263.             android:layout_height="40dp"
  264.             android:gravity="right"
  265.             android:id="@+id/longLabel" />
  266.         <EditText
  267.             android:layout_width="150dp"
  268.             android:layout_height="50dp"
  269.             android:id="@+id/longText"
  270.             android:textAppearance="?android:attr/textAppearanceMedium"
  271.             android:layout_marginLeft="5dp" />
  272.     </LinearLayout>
  273.     <LinearLayout
  274.         android:orientation="vertical"
  275.         android:layout_marginTop="28dp"
  276.         android:layout_width="match_parent"
  277.         android:layout_height="wrap_content"
  278.         android:gravity="center_horizontal"
  279.         android:id="@+id/getSection">
  280.         <Button
  281.             android:id="@+id/getWeatherButton"
  282.             android:layout_width="300dp"
  283.             android:layout_height="wrap_content"
  284.             android:gravity="center_horizontal"
  285.             android:textAppearance="?android:attr/textAppearanceLarge"
  286.             android:text="Get Weather" />
  287.     </LinearLayout>
  288.     <LinearLayout
  289.         android:orientation="horizontal"
  290.         android:layout_marginTop="30dp"
  291.         android:layout_marginLeft="40dp"
  292.         android:layout_marginRight="40dp"
  293.         android:layout_width="match_parent"
  294.         android:layout_height="wrap_content"
  295.         android:id="@+id/locSection">
  296.         <TextView
  297.             android:text="Location:"
  298.             android:textAppearance="?android:attr/textAppearanceMedium"
  299.             android:layout_width="120dp"
  300.             android:layout_height="30dp"
  301.             android:gravity="left"
  302.             android:id="@+id/locLabel" />
  303.         <TextView
  304.             android:text=""
  305.             android:textAppearance="?android:attr/textAppearanceMedium"
  306.             android:layout_width="wrap_content"
  307.             android:layout_height="60dp"
  308.             android:gravity="left"
  309.             android:id="@+id/locationText" />
  310.     </LinearLayout>
  311.     <LinearLayout
  312.         android:orientation="horizontal"
  313.         android:layout_marginTop="10dp"
  314.         android:layout_marginLeft="40dp"
  315.         android:layout_marginRight="40dp"
  316.         android:layout_width="match_parent"
  317.         android:layout_height="wrap_content"
  318.         android:id="@+id/tempSection">
  319.         <TextView
  320.             android:text="Temperature:"
  321.             android:textAppearance="?android:attr/textAppearanceMedium"
  322.             android:layout_width="120dp"
  323.             android:layout_height="30dp"
  324.             android:gravity="left"
  325.             android:id="@+id/tempLabel" />
  326.         <TextView
  327.             android:text=""
  328.             android:textAppearance="?android:attr/textAppearanceMedium"
  329.             android:layout_width="wrap_content"
  330.             android:layout_height="30dp"
  331.             android:gravity="left"
  332.             android:id="@+id/tempText" />
  333.     </LinearLayout>
  334.     <LinearLayout
  335.         android:orientation="horizontal"
  336.         android:layout_marginTop="10dp"
  337.         android:layout_marginLeft="40dp"
  338.         android:layout_marginRight="40dp"
  339.         android:layout_width="match_parent"
  340.         android:layout_height="wrap_content"
  341.         android:id="@+id/humidSection">
  342.         <TextView
  343.             android:text="Humidity:"
  344.             android:textAppearance="?android:attr/textAppearanceMedium"
  345.             android:layout_width="120dp"
  346.             android:layout_height="30dp"
  347.             android:gravity="left"
  348.             android:id="@+id/humidLabel" />
  349.         <TextView
  350.             android:text=""
  351.             android:textAppearance="?android:attr/textAppearanceMedium"
  352.             android:layout_width="wrap_content"
  353.             android:layout_height="30dp"
  354.             android:gravity="left"
  355.             android:id="@+id/humidText" />
  356.     </LinearLayout>
  357.     <LinearLayout
  358.         android:orientation="horizontal"
  359.         android:layout_marginTop="10dp"
  360.         android:layout_marginLeft="40dp"
  361.         android:layout_marginRight="40dp"
  362.         android:layout_width="match_parent"
  363.         android:layout_height="wrap_content"
  364.         android:id="@+id/condSection">
  365.         <TextView
  366.             android:text="Conditions:"
  367.             android:textAppearance="?android:attr/textAppearanceMedium"
  368.             android:layout_width="120dp"
  369.             android:layout_height="30dp"
  370.             android:gravity="left"
  371.             android:id="@+id/condLabel" />
  372.         <TextView
  373.             android:text=""
  374.             android:textAppearance="?android:attr/textAppearanceMedium"
  375.             android:layout_width="wrap_content"
  376.             android:layout_height="60dp"
  377.             android:gravity="left"
  378.             android:id="@+id/condText" />
  379.     </LinearLayout>
  380.     <LinearLayout
  381.         android:orientation="horizontal"
  382.         android:layout_marginTop="10dp"
  383.         android:layout_marginLeft="40dp"
  384.         android:layout_marginRight="40dp"
  385.         android:layout_width="match_parent"
  386.         android:layout_height="wrap_content"
  387.         android:id="@+id/pressureSection">
  388.         <TextView
  389.             android:text="Barometer:"
  390.             android:textAppearance="?android:attr/textAppearanceMedium"
  391.             android:layout_width="120dp"
  392.             android:layout_height="30dp"
  393.             android:gravity="left"
  394.             android:id="@+id/pressureLabel" />
  395.         <TextView
  396.             android:text=""
  397.             android:textAppearance="?android:attr/textAppearanceMedium"
  398.             android:layout_width="wrap_content"
  399.             android:layout_height="30dp"
  400.             android:gravity="left"
  401.             android:id="@+id/pressureText" />
  402.     </LinearLayout>
  403. </LinearLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement