فهرست منبع

Location V1 API implemented.

While the app is running, Gasteizko Margolariak's locations is checked periodically with the Location V1 API. If location found, the menu entry and the section in the home fragment is shown (and hidden otherwise).
seavenois 9 سال پیش
والد
کامیت
4dd3eda897

+ 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.

+ 40 - 42
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,48 @@ 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.GONE);
+			findViewById(R.id.ll_home_section_location).setVisibility(View.GONE);
+		}
+		else {
+			findViewById(R.id.rl_menu_location).setVisibility(View.VISIBLE);
+			findViewById(R.id.ll_home_section_location).setVisibility(View.VISIBLE);
+		}
+	}
+
 	//Not referenced in code.
 	public void showMenu(View v) {
 		PopupMenu popup = new PopupMenu(this, v);
@@ -304,7 +285,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);
@@ -625,7 +606,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 +692,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);
+	}
+
+}