Explorar o código

Merge branch 'LocationV1API'

seavenois %!s(int64=9) %!d(string=hai) anos
pai
achega
6e0b397fe8

+ 1 - 1
app/src/main/java/com/ivalentin/margolariak/GM.java

@@ -114,7 +114,7 @@ final class GM {
 				/**
 				 * Creates the table "location" on the database.
 				 */
-				static final String LOCATION = "CREATE TABLE IF NOT EXISTS location (id INT, dtime DATETIME, lat FLOAT, lon FLOAT, manual INT);";
+				static final String LOCATION = "CREATE TABLE IF NOT EXISTS location (dtime DATETIME, lat DOUBLE, lon DOUBLE);";
 
 				/**
 				 * Creates the table "notification" on the database.

+ 25 - 42
app/src/main/java/com/ivalentin/margolariak/HomeLayout.java

@@ -8,6 +8,7 @@ import java.util.Locale;
 
 import android.annotation.SuppressLint;
 import android.Manifest;
+import android.app.Activity;
 import android.content.Context;
 import android.content.Intent;
 import android.content.SharedPreferences;
@@ -55,8 +56,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 
 	@Override
 	public boolean onOptionsItemSelected(MenuItem item) {
-		// TODO Auto-generated method stub
-		Log.e("MENU", "FROM HOME");
 		return false;
 	}
 
@@ -81,39 +80,12 @@ public class HomeLayout extends Fragment implements LocationListener {
 		//Load the layout.
 		view = inflater.inflate(R.layout.fragment_layout_home, null);
 
-		//Variable to know if I need a location manager
-		//boolean requestLocation = false;
-
-		//Show tutorial if its the first time
-		/*final SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREF, Context.MODE_PRIVATE);
-		if (!preferences.getBoolean(GM.PREF_TUTORIAL, false)) {
-			final RelativeLayout llTutorial = (RelativeLayout) getActivity().findViewById(R.id.rl_tutorial);
-			llTutorial.setVisibility(View.VISIBLE);
-			llTutorial.setOnTouchListener(new View.OnTouchListener() {
-				@Override
-				public boolean onTouch(View v, MotionEvent event) {
-					return true;
-				}
-			});
-			Button btTutorial = (Button) getActivity().findViewById(R.id.bt_tutorial);
-			btTutorial.setOnClickListener(new OnClickListener() {
-				@Override
-				public void onClick(View v) {
-					llTutorial.setVisibility(View.GONE);
-					SharedPreferences.Editor editor = preferences.edit();
-					editor.putBoolean(GM.PREF_TUTORIAL, true);
-					editor.apply();
-				}
-			});
-		}*/
-
 		//Request location permissions if not set
 		if (ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
 			ActivityCompat.requestPermissions(this.getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, GM.PERMISSION.LOCATION);
 		}
 
 		//Set Location manager
-		//TODO: Only do this if location is required
 		locationManager = (LocationManager) view.getContext().getSystemService(Context.LOCATION_SERVICE);
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.requestLocationUpdates(locationManager.getBestProvider(new Criteria(), true), GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
@@ -496,12 +468,25 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 * @return True if the section has been shown, false otherwise.
 	 */
 	private boolean setUpLocation(Location location, View view) {
-		SharedPreferences preferences = view.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		//TODO Do this from db
-		/*if (!preferences.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
-			try {
-				Double lat = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-				Double lon = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
+		try {
+
+			Double lat, lon;
+
+			SQLiteDatabase db = getActivity().openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+			Cursor cursor;
+			cursor = db.rawQuery("SELECT lat, lon FROM location WHERE dtime >= Datetime('now', '-10 minutes') ORDER BY dtime DESC LIMIT 1;", null);
+			if (cursor.getCount() == 0){
+				cursor.close();
+				db.close();
+				return false;
+			}
+			else {
+				cursor.moveToFirst();
+				lat = cursor.getDouble(0);
+				lon = cursor.getDouble(1);
+				cursor.close();
+				db.close();
+
 				Double distance = Distance.calculateDistance(lat, lon, location.getLatitude(), location.getLongitude());
 				TextView text = (TextView) view.findViewById(R.id.tv_home_section_location_distance);
 				if (distance <= 2) {
@@ -510,13 +495,14 @@ public class HomeLayout extends Fragment implements LocationListener {
 				} else {
 					text.setText(String.format(getString(R.string.home_section_location_text_long), String.format(Locale.US, "%.02f", distance)));
 				}
+
 				return true;
 			}
-			catch (Exception ex){
-				Log.e("Location", "Couldn't set up home location section: " + ex.toString());
-			}
+		}
+		catch (Exception ex){
+			Log.e("Location", "Couldn't set up home location section: " + ex.toString());
+		}
 
-		}*/
 		return false;
 	}
 
@@ -1057,7 +1043,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onPause() {
-		//TODO: Only do this if location is required
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.removeUpdates(this);
 		}
@@ -1071,7 +1056,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onDestroy() {
-		//TODO: Only do this if location is required
 		try {
 			if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 				locationManager.removeUpdates(this);
@@ -1091,7 +1075,6 @@ public class HomeLayout extends Fragment implements LocationListener {
 	 */
 	@Override
 	public void onResume(){
-		//TODO: Only do this if location is required
 		if (!(ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(view.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
 		}

+ 93 - 33
app/src/main/java/com/ivalentin/margolariak/LocationLayout.java

@@ -9,17 +9,21 @@ import com.google.android.gms.maps.MapsInitializer;
 import com.google.android.gms.maps.OnMapReadyCallback;
 import com.google.android.gms.maps.model.BitmapDescriptorFactory;
 import com.google.android.gms.maps.model.LatLng;
+import com.google.android.gms.maps.model.Marker;
 import com.google.android.gms.maps.model.MarkerOptions;
 
+import android.app.Activity;
 import android.content.Context;
-import android.content.SharedPreferences;
 import android.content.pm.PackageManager;
+import android.database.Cursor;
+import android.database.sqlite.SQLiteDatabase;
 import android.location.Criteria;
 import android.location.Location;
 import android.location.LocationListener;
 import android.location.LocationManager;
 import android.os.Bundle;
 import android.app.Fragment;
+import android.os.Handler;
 import android.support.v4.app.ActivityCompat;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -42,7 +46,7 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 
 	//The map view
 	private MapView mapView;
-	private MarkerOptions moGm;
+	GoogleMap gMap;
 
 	private LocationManager locationManager;
 
@@ -52,6 +56,35 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	//The main View
 	private View v;
 
+	private double lat, lon;
+
+	//Map marker
+	Marker gmMarker;
+	MarkerOptions moGm = new MarkerOptions();
+
+	private final Handler markerHandler = new Handler();
+
+	private final Runnable resetMarker = new Runnable() {
+		@Override
+		public void run() {
+
+			if (gmMarker != null) {
+				gmMarker.remove();
+				if (refreshLocation()) {
+					gmMarker.setPosition(new LatLng(lat, lon));
+					gmLocation = new LatLng(lat, lon);
+					//moGm = new MarkerOptions();
+					moGm.title(v.getContext().getString(R.string.app_name));
+					moGm.position(gmLocation);
+					moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
+					gmMarker = gMap.addMarker(moGm);
+				}
+			}
+			markerHandler.postDelayed(resetMarker, GM.LOCATION.INTERVAL);
+		}
+	};
+
+
 	/**
 	 * Run when the fragment is inflated.
 	 *
@@ -76,6 +109,12 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		//Set the title
 		((MainActivity) getActivity()).setSectionTitle(v.getContext().getString(R.string.menu_location));
 
+		//Refresh the location.
+		refreshLocation();
+
+		//Periodically check map
+		markerHandler.post(resetMarker);
+
 		mapView = (MapView) v.findViewById(R.id.mapview);
 		mapView.onCreate(savedInstanceState);
 
@@ -101,6 +140,8 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 			locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, GM.LOCATION.ACCURACY.TIME, GM.LOCATION.ACCURACY.SPACE, this);
 		}
 		super.onResume();
+
+		markerHandler.post(resetMarker);
 	}
 
 	/**
@@ -114,6 +155,8 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 			locationManager.removeUpdates(this);
 		}
 		super.onPause();
+
+		markerHandler.removeCallbacks(resetMarker);
 	}
 
 	/**
@@ -128,10 +171,13 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			locationManager.removeUpdates(this);
 		}
+
 		if (mapView != null){
 			mapView.onResume();
 			mapView.onDestroy();
 		}
+
+		markerHandler.removeCallbacks(resetMarker);
 	}
 
 	/**
@@ -149,6 +195,34 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		}
 	}
 
+	/**
+	 * Refresh the global variables "lat" and "lon".
+	 *
+	 * Uses the most recent data in the database, if they are not older than 10 minutes.
+	 *
+	 * @return true if there is a location from less than 10 minutes ago, 0 otherwise.
+	 */
+	private boolean refreshLocation(){
+
+		SQLiteDatabase db = getActivity().openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+		Cursor cursor;
+		cursor = db.rawQuery("SELECT lat, lon FROM location WHERE dtime >= Datetime('now', '-10 minutes') ORDER BY dtime DESC LIMIT 1;", null);
+		if (cursor.getCount() == 0){
+			cursor.close();
+			db.close();
+			return false;
+		}
+		else {
+			cursor.moveToFirst();
+			lat = cursor.getDouble(0);
+			lon = cursor.getDouble(1);
+			cursor.close();
+			db.close();
+			return true;
+		}
+
+	}
+
 	/**
 	 * Called when the map is ready to be used. 
 	 * Initializes it and sets the Gasteizko Margolariak marker.
@@ -160,6 +234,8 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	@Override
 	public void onMapReady(GoogleMap googleMap) {
 
+		gMap = googleMap;
+
 		if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
 			googleMap.setMyLocationEnabled(true);
 		}
@@ -171,19 +247,18 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		} catch (Exception e) {
 			Log.e("Error initializing maps", e.toString());
 		}
-		
-		//Set GM marker
-		//TODO: Use db
-		SharedPreferences preferences = v.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		Double lat = 0.0; //Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-		Double lon = 0.0; //Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
-		gmLocation = new LatLng(lat, lon);
-		moGm = new MarkerOptions();
-		moGm.title(v.getContext().getString(R.string.app_name));
-		moGm.position(gmLocation);
-		moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
-		googleMap.addMarker(moGm);
-		googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 14.0f));
+
+		//If there is a location, set it
+		if (refreshLocation()) {
+
+			//Set the marker
+			gmLocation = new LatLng(lat, lon);
+			moGm.title(v.getContext().getString(R.string.app_name));
+			moGm.position(gmLocation);
+			moGm.icon(BitmapDescriptorFactory.fromResource(R.drawable.pinpoint_gm));
+			gmMarker = googleMap.addMarker(moGm);
+			googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lon), 14.0f));
+		}
 
 		//Start device location requests
 		if (!(ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(v.getContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
@@ -192,10 +267,11 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 		}
 	}
 
+
 	private void calCulateDistance(Location userLocation){
 		TextView text = (TextView) v.findViewById(R.id.tv_location_distance);
 		try {
-			Double distance = Distance.calculateDistance(userLocation.getLatitude(), userLocation.getLongitude(), gmLocation.latitude, gmLocation.longitude);
+			Double distance = Distance.calculateDistance(userLocation.getLatitude(), userLocation.getLongitude(), lat, lon);
 			if (distance <= 2) {
 				distance = 1000 * distance;
 				text.setText(String.format(getString(R.string.home_section_location_text_short), distance.intValue(), (int) (0.012 * distance.intValue())));
@@ -220,24 +296,11 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	 */
 	@Override
 	public void onLocationChanged(Location location) {
-		//TODO: Read again the GM Location.
-		//TODO From database
-		/*SharedPreferences preferences = v.getContext().getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-		if (!preferences.getString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION).equals(GM.DEFAULT_PREF_GM_LOCATION)) {
-
-			Double lat = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LATITUDE, 0));
-			Double lon = Double.longBitsToDouble(preferences.getLong(GM.PREF_GM_LONGITUDE, 0));
-			gmLocation = new LatLng(lat, lon);
-						calCulateDistance(location);
-			if (moGm != null){
-				moGm.visible(true);
-			}
-		}*/
+		calCulateDistance(location);
 	}
 
 	/**
 	 * Called when the location provider changes it's state.
-	 * Recalculates the list of events in the around section.
 	 *
 	 * @param provider The name of the provider
 	 * @param status Status code of the provider
@@ -276,7 +339,4 @@ public class LocationLayout extends Fragment implements OnMapReadyCallback, Loca
 	public void onProviderDisabled(String provider) {
 		//populateAround();
 	}
-
-
-
 }

+ 44 - 44
app/src/main/java/com/ivalentin/margolariak/MainActivity.java

@@ -2,9 +2,6 @@ package com.ivalentin.margolariak;
 
 import java.math.BigInteger;
 import java.security.SecureRandom;
-import java.text.SimpleDateFormat;
-import java.util.Calendar;
-import java.util.Locale;
 
 import android.app.Activity;
 import android.app.Fragment;
@@ -55,64 +52,52 @@ public class MainActivity extends Activity {
 	//Alarm to get location and notifications.
 	private AlarmReceiver notificationAlarm;
 
-	//The menu entries
-	private RelativeLayout menuItem[];
 	private TextView menuText[];
 	private ImageView menuImage[];
 
 	//Handler to periodically check for location updates
 	private final Handler locationHandler = new Handler();
 	// Code to check for location updates
+	private MainActivity activity = this;
 	private final Runnable checkForLocation = new Runnable() {
 		@Override
 		public void run() {
 
-			//Get location page and parse it
-			boolean result = false;
-			FetchURL fu = new FetchURL();
-			//TODO: This needs a simple API too
-			fu.Run(GM.API.SERVER + "/app/location.php");
-			String lat = "", lon = "";
-			String o = fu.getOutput().toString();
-			Log.d("Location", "Fetched location page");
-			if (o.contains("<location>none</location>"))
-				result = false;
-			if (o.contains("<lat>") && o.contains("<lon>")) {
-				lat = o.substring(o.indexOf("<lat>") + 5, o.indexOf("</lat>"));
-				lon = o.substring(o.indexOf("<lon>") + 5, o.indexOf("</lon>"));
-				result = true;
-			}
-
-			//TODO: Store in database
-			SharedPreferences settings = getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
-			SharedPreferences.Editor editor = settings.edit();
-			if (result) {
-				//TODO editor.putLong(GM.PREF_GM_LATITUDE, Double.doubleToLongBits(Double.parseDouble(lat)));
-				//TODO editor.putLong(GM.PREF_GM_LONGITUDE, Double.doubleToLongBits(Double.parseDouble(lon)));
-				//TODO editor.putString(GM.PREF_GM_LOCATION, new SimpleDateFormat("yyyyMMddHHmmss", Locale.US).format(Calendar.getInstance().getTime()));
-
-				//Show menu entry
-				if (menuItem[1] != null) {
-					menuItem[1].setVisibility(View.VISIBLE);
-				}
-			} else {
-				//TODO editor.putString(GM.PREF_GM_LOCATION, GM.DEFAULT_PREF_GM_LOCATION);
-				if (menuItem[1] != null) {
-					menuItem[1].setVisibility(View.GONE);
-				}
-			}
-			editor.apply();
+			new ReceiveLocation(activity).execute();
 
 			//Repeat this the same runnable code block again another th specified interval
 			locationHandler.postDelayed(checkForLocation, GM.LOCATION.INTERVAL);
 		}
 	};
+
 	/**
 	 * ATTENTION: This was auto-generated to implement the App Indexing API.
 	 * See https://g.co/AppIndexing/AndroidStudio for more information.
 	 */
 	private GoogleApiClient client;
 
+	/**
+	 * Enables o disables the location section.
+	 *
+	 * Shows or hiddes the menu entry and the home fragment,
+	 *
+	 * @param report True to show, false to hide.
+	 */
+	public void gotLocation(boolean report){
+		if (report) {
+			findViewById(R.id.rl_menu_location).setVisibility(View.VISIBLE);
+			if (findViewById(R.id.ll_home_section_location) != null){
+				findViewById(R.id.ll_home_section_location).setVisibility(View.VISIBLE);
+			}
+		}
+		else {
+			findViewById(R.id.rl_menu_location).setVisibility(View.GONE);
+			if (findViewById(R.id.ll_home_section_location) != null) {
+				findViewById(R.id.ll_home_section_location).setVisibility(View.GONE);
+			}
+		}
+	}
+
 	//Not referenced in code.
 	public void showMenu(View v) {
 		PopupMenu popup = new PopupMenu(this, v);
@@ -304,7 +289,7 @@ public class MainActivity extends Activity {
 		setContentView(R.layout.activity_main);
 
 		//Assign menu items
-		menuItem = new RelativeLayout[6];
+		RelativeLayout[] menuItem = new RelativeLayout[6];
 		menuItem[0] = (RelativeLayout) findViewById(R.id.rl_menu_home);
 		menuItem[1] = (RelativeLayout) findViewById(R.id.rl_menu_location);
 		menuItem[2] = (RelativeLayout) findViewById(R.id.rl_menu_lablanca);
@@ -372,8 +357,6 @@ public class MainActivity extends Activity {
 		SharedPreferences sharedData = getSharedPreferences(GM.PREFERENCES.PREFERNCES, Context.MODE_PRIVATE);
 		SharedPreferences.Editor dataEditor = sharedData.edit();
 
-		//TODO: Read database. If there is a recent location, show the menu entry
-
 		//If the user code is not set, generate one
 		if (sharedData.getString(GM.DATA.KEY.USER, GM.DATA.DEFAULT.USER).length() == GM.DATA.DEFAULT.USER.length()) {
 			SecureRandom random = new SecureRandom();
@@ -625,7 +608,6 @@ public class MainActivity extends Activity {
 	 * Creates the app database and fills it with the hard coded, default data.
 	 */
 	private void deleteDatabase() {
-		SQLiteDatabase db;
 		try {
 			getApplicationContext().deleteDatabase(GM.DB.NAME);
 		} catch (Exception ex) {
@@ -712,18 +694,36 @@ public class MainActivity extends Activity {
 		return super.onKeyUp(keyCode, event);
 	}
 
+	/**
+	 * Overrides onResume().
+	 * Resumes the location handler to check for location regularly.
+	 *
+	 * @see Activity#onResume()
+	 */
 	@Override
 	public void onResume() {
 		locationHandler.post(checkForLocation);
 		super.onResume();
 	}
 
+	/**
+	 * Overrides onPause().
+	 * Stops the location handler to check for location regularly.
+	 *
+	 * @see Activity#onPause()
+	 */
 	@Override
 	public void onPause() {
 		locationHandler.removeCallbacks(checkForLocation);
 		super.onPause();
 	}
 
+	/**
+	 * Overrides onDestroy().
+	 * Stops the location handler to check for location regularly.
+	 *
+	 * @see Activity#onDestroy()
+	 */
 	@Override
 	public void onDestroy() {
 		locationHandler.removeCallbacks(checkForLocation);

+ 101 - 0
app/src/main/java/com/ivalentin/margolariak/ReceiveLocation.java

@@ -0,0 +1,101 @@
+package com.ivalentin.margolariak;
+
+import android.app.Activity;
+import android.database.sqlite.SQLiteDatabase;
+import android.os.AsyncTask;
+import android.util.Log;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+
+/**
+ * AsyncTask to get Gasteizko Margolariak location.
+ *
+ * Uses the Location V1 API.
+ *
+ * @author Inigo Valentin
+ *
+ * @see AsyncTask
+ */
+
+class ReceiveLocation extends AsyncTask<Void, Void, Void> {
+
+	private MainActivity activity;
+	private boolean report = false;
+
+	/**
+	 * Called when the AsyncTask is created.
+	 *
+	 * @param activity The calling activity.
+	 */
+	ReceiveLocation(MainActivity activity){
+		this.activity = activity;
+	}
+
+	@Override
+	protected Void doInBackground(Void... params) {
+
+		try {
+			String uri = GM.API.SERVER + GM.API.LOCATION.PATH;
+			URL url = new URL(uri);
+			HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
+
+			int httpCode = urlConnection.getResponseCode();
+			switch (httpCode) {
+				case 400:	//Client error: Bad request
+					Log.e("LOCATION", "The server returned a 400 code (Client Error: Bad request) for the url \"" + uri + "\"");
+					break;
+				case 204:	//Success: No content
+					Log.d("LOCATION", "The server returned a 204 code (Success: No content) for the url \"" + uri + "\". Not getting location...");
+					break;
+				case 200:	//Success: OK
+					Log.d("LOCATION", "The server returned a 200 code (Success: OK) for the url \"" + uri + "\". Now getting location...");
+					BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
+					StringBuilder sb = new StringBuilder();
+					String o;
+					while ((o = br.readLine()) != null) {
+						sb.append(o);
+					}
+
+					//Get the string with the sync json. (The whole page)
+					String strLocation = sb.toString();
+					String lat = strLocation.substring(strLocation.indexOf("\"lat\":\"") + 7, strLocation.indexOf("\"", strLocation.indexOf("\"lat\":\"") + 8));
+					String lon = strLocation.substring(strLocation.indexOf("\"lon\":\"") + 7, strLocation.indexOf("\"", strLocation.indexOf("\"lon\":\"") + 8));
+					String dtime = strLocation.substring(strLocation.indexOf("\"dtime\":\"") + 9, strLocation.indexOf("\"", strLocation.indexOf("\"dtime\":\"") + 10));
+					Log.d("LOCATION", "Found location [" +lat + ", " + lon + "] sent " + dtime);
+
+					//Insert into the database
+					SQLiteDatabase db = activity.openOrCreateDatabase(GM.DB.NAME, Activity.MODE_PRIVATE, null);
+					db.execSQL("INSERT INTO location VALUES ('" + dtime + "', " + lat + ", " + lon + ")");
+					db.close();
+
+					//Set to true so the menu and relevant sections are hidden.
+					report = true;
+			}
+
+
+		} catch (MalformedURLException e) {
+			Log.e("LOCATION", "Unable to get location, malformed URL: " + e.toString());
+		} catch (IOException e) {
+			Log.e("LOCATION", "Unable to get location, IO exception: " + e.toString());
+		}
+
+
+		return null;
+	}
+
+	/**
+	 * Things to do after sync. Shows or hides the menu entry and relevant sections.
+	 *
+	 * @see android.os.AsyncTask#onPreExecute()
+	 */
+	@Override
+	protected void onPostExecute(Void v){
+		activity.gotLocation(report);
+	}
+
+}