Android location services are very popular these days, they provide the location of a device in the form of latitude and longitude coordinates using with we can track the location up to 10 meters of accuracy. Location services provide many other parameters of a device like speed, the direction of movement, human-readable address using Geocoder service.
This tutorial is the second part of the previous one, please visit part 1 here before going through this post.
Let’s continue on the implementation of Background Geolocation Service in Android Device.
Create a Location BroadcastReciever
Create a new broadcast and name it LocationUpdatesBroadcastReceiver.java, in this file, we will onReceive method which will be called and in turn, will call the getLocationUpdates method in Utils class.
The setLocationUpdatesResult method will change in SharedPreference value to update text having the address and other details when the application is open.
LocationUpdatesBroadcastReceiver.java will look as below:
package com.freakyjolly.demobackgroundlocation; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import java.text.DateFormat; import java.util.Date; public class LocationUpdatesBroadcastReceiver extends BroadcastReceiver { private static final String TAG = "LUBroadcastReceiver"; public static final String ACTION_PROCESS_UPDATES = "com.freakyjolly.demobackgroundlocation.action" + ".PROCESS_UPDATES"; @Override public void onReceive(Context context, Intent intent) { if (intent != null) { final String action = intent.getAction(); if (ACTION_PROCESS_UPDATES.equals(action)) { Utils.setLocationUpdatesResult(context, DateFormat.getDateTimeInstance().format(new Date())); Utils.getLocationUpdates(context,intent,"PROCESS_UPDATES"); } } } }
Next, we will create a SharedPreference Utils class named LocationRequestHelper.java.
What is SharedPreference in Android?
If you have a relatively small collection of key-values that you’d like to save, you should use the
<a href="https://developer.android.com/reference/android/content/SharedPreferences.html">SharedPreferences</a>
APIs. A<a href="https://developer.android.com/reference/android/content/SharedPreferences.html">SharedPreferences</a>
object points to a file containing key-value pairs and provides simple methods to read and write them. Each<a href="https://developer.android.com/reference/android/content/SharedPreferences.html">SharedPreferences</a>
file is managed by the framework and can be private or shared.
This file is having some methods to save and get the different type of data like string, boolean, object etc, we have not used all of them but it’s better to keep all of them
LocationRequestHelper.java file will look this
package com.freakyjolly.demobackgroundlocation; import android.content.Context; import android.content.SharedPreferences; public class LocationRequestHelper { private static LocationRequestHelper mSharedPreferenceUtils; protected Context mContext; private SharedPreferences mSharedPreferences; private SharedPreferences.Editor mSharedPreferencesEditor; private LocationRequestHelper(Context context) { mContext = context; mSharedPreferences = context.getSharedPreferences("com.freakyjolly.demobackgroundlocation", Context.MODE_PRIVATE); mSharedPreferencesEditor = mSharedPreferences.edit(); } public static synchronized LocationRequestHelper getInstance(Context context) { if (mSharedPreferenceUtils == null) { mSharedPreferenceUtils = new LocationRequestHelper(context.getApplicationContext()); } return mSharedPreferenceUtils; } /** * Stores String value in preference */ public void setValue(String key, String value) { mSharedPreferencesEditor.putString(key, value); mSharedPreferencesEditor.commit(); } /** * Stores int value in preference */ public void setValue(String key, int value) { mSharedPreferencesEditor.putInt(key, value); mSharedPreferencesEditor.commit(); } /** * Stores Double value in String format in preference */ public void setValue(String key, double value) { setValue(key, Double.toString(value)); } /** * Stores long value in preference */ public void setValue(String key, long value) { mSharedPreferencesEditor.putLong(key, value); mSharedPreferencesEditor.commit(); } /** * Stores boolean value in preference */ public void setValue(String key, boolean value) { mSharedPreferencesEditor.putBoolean(key, value); mSharedPreferencesEditor.commit(); } /** * Retrieves String value from preference */ public String getStringValue(String key, String defaultValue) { return mSharedPreferences.getString(key, defaultValue); } /** * Retrieves int value from preference */ public int getIntValue(String key, int defaultValue) { return mSharedPreferences.getInt(key, defaultValue); } /** * Retrieves long value from preference */ public long getLongValue(String key, long defaultValue) { return mSharedPreferences.getLong(key, defaultValue); } /** * Retrieves boolean value from preference */ public boolean getBoolanValue(String keyFlag, boolean defaultValue) { return mSharedPreferences.getBoolean(keyFlag, defaultValue); } /** * Removes key from preference * * @param key key of preference that is to be deleted */ public void removeKey(String key) { if (mSharedPreferencesEditor != null) { mSharedPreferencesEditor.remove(key); mSharedPreferencesEditor.commit(); } } /** * Clears all the preferences stored */ public void clear() { mSharedPreferencesEditor.clear().commit(); } }
Update activity_main.xml layout file under res>layout folder in the project with the following code
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/activity_main"
tools:context=".MainActivity">
<Button
android:id="@+id/request_updates_button"
android:layout_width="276dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentRight="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@android:color/holo_green_dark"
android:onClick="requestLocationUpdates"
android:text="@string/request_updates"
android:textColor="@color/startUpdate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
<Button
android:id="@+id/remove_updates_button"
android:layout_width="276dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:background="@android:color/holo_red_light"
android:onClick="removeLocationUpdates"
android:text="@string/remove_updates"
android:textColor="@color/removeUpdate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />
<TextView
android:id="@+id/location_updates_result"
android:layout_width="325dp"
android:layout_height="237dp"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="44dp"
android:paddingLeft="30dp"
android:paddingTop="10dp"
android:paddingRight="30dp"
android:paddingBottom="10dp"
android:text="test"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.511"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView"
app:layout_constraintVertical_bias="0.651" />
<ImageView
android:id="@+id/imageView"
android:layout_width="139dp"
android:layout_height="125dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:srcCompat="@drawable/logo" />
</android.support.constraint.ConstraintLayout>
Finally, our project directory structure will look like this
Now run the application in a real device to check if it’s working as expected. Let me know if you face some issue regarding the same.
Find full sample source code on Github here
Leave a Reply