Android - Android Studio                             Home : www.sharetechnote.com

 

 

 

 

Location Service

 

The sample programs shown in the First App page and Hello World page were just for getting familiar with the development environment. They were not so meaningful in terms of programming.

The sample program in this page would be considered as real / meaningful application even though it doesn't look fancy (actually very primitive).

Main core of most of the Apps would be to utilize various hardware resources like GPS, Camera, Memory etc embedded in the device (Smart Phone). Google has already developed various libraries that enable you to utilize these hardware resources just with several lines of code.

You will see a case of using the GPS embedded in a mobile phone and you will learn how to utilize the built-in libraries to utilize the GPS module.

 

NOTE : Actually writing the code for Location Service is not so complicated but to make it work may not be that easy if you don't know about a simple trick. Android (probably other operating system as well) is very sensitive about collecting personal information.  Location information is considered as one of those sensitive information. To retrieve (collect) those information from a Smart Phone, the application needs an approval from the user. So handling those approval process is an important steps to be implemented in this App.

A good idea to approve this kind of information collection even before you run this app would be to Google Map application. Since Google Map is highly dependent on Location service, it will popup a dialog asking if you will allow to retrieve the location information and allow it from the dialog box. If it does not popup those dialog and allow you to use the map, it indicates that you have allowed it some time before. Then you can easily run your own Location based App.

 

 

Example 01 > Basic Location Update

 

Now let's create an App with very simple user interface and very basic way of collecting location information. With this very simple code, you would be able to read the location data but the data may not always be the latest data. It implies that the App does not get updated with location data in real time. This issue will be handled in the next example, but for the first example I prefer to keep the simpler code in order not to scare you too much :)

 

First, create a simple user interface as shown below (If you are not familiar with how to get to this screen, refer to Hello World page).

 

 

 

Assign an ID to the multiline Textbox as shown below.

 

 

 

Assign an ID to the Button as shown below.

 

 

 

Now open the Manifest.xml file and add user perission line as shown below. (The screenshot does not show the full text. See the full text below the screenshot)

 

 

Following is the full text of the Manifest.xml file.

 

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.android.location_01">

 

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

 

</manifest>

 

 

Now write the routine in MainActivity.java to read the location data and print it out in the text box (The full text is shown below the screenshot)

 

 

 

Following is the full text of the source code and I highlighed the text you would need to add to the default source code. The red part is the code that is directly related to utilizing Location Service library and the blue part is the code that are mostly to display the data onto the user interface.

 

    package com.example.android.location_01;

    import android.Manifest;

    import android.content.Context;

    import android.content.pm.PackageManager;

    import android.os.Bundle;

    import android.widget.TextView;

    import android.view.View;

    import android.location.Location;

    import android.location.LocationManager;

    import android.support.v4.app.ActivityCompat;

    import android.support.v7.app.AppCompatActivity;

     

    public class MainActivity extends AppCompatActivity {

     

        TextView CoordList;

        String strTmp;

     

        static final int REQUEST_LOCATION = 1;

        LocationManager locationManager;

        Location coord;

     

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            CoordList = (TextView)findViewById(R.id.txtCoord);

            locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

     

            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED &&

                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED){

                ActivityCompat.requestPermissions(this,

                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

                CoordList.setText("Premission Request");

            } else {

                CoordList.setText("Already Got the Permission. So No Request");

            };

     

     

        }

     

        public void btnUpdate_Click(View v) {

     

            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED &&

                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED){

     

                ActivityCompat.requestPermissions(this,

                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

                CoordList.setText("Premission Request");

     

            } else {

                 CoordList.setText("");

            };

     

            coord = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     

            if (coord != null) {

                double lattitude = coord.getLatitude();

                double longitude = coord.getLongitude();

                CoordList.setText("Latitude = " + String.format("%5.2f",lattitude) +

                                  "\nLongitude = " + String.format("%5.2f",longitude));

            } else {

                CoordList.setText("No Location data available");

            };

        }

    }

 

 

Now it's time to run. If you run the App, you would get a screen as shown on the left side. If you tap the [UPDATE] button, you will get the location data printed out as shown on the right.

 

 

 

 

Example 02 > Automatic Location Update

 

In previous example, you may not get the latest and current location information even if the GPS has new location data. In this example, I modified the scenario a little bit so that we can always get the latest location data whenever you tap on [UPDATE] button.

 

    package com.example.android.location_01;

    import android.Manifest;

    import android.content.Context;

    import android.content.pm.PackageManager;

    import android.os.Bundle;

    import android.widget.TextView;

    import android.view.View;

    import android.location.Location;

    import android.location.LocationManager;

    import android.location.LocationListener;

    import android.support.v4.app.ActivityCompat;

    import android.support.v7.app.AppCompatActivity;

     

    public class MainActivity extends AppCompatActivity  implements LocationListener {

     

        TextView CoordList;

        String strTmp;

     

        static final int REQUEST_LOCATION = 1;

        LocationManager locationManager;

        Location coord;

     

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

     

            CoordList = (TextView)findViewById(R.id.txtCoord);

     

            locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

            GetPermission();

            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 1, this);

     

        }

     

        @Override

        public void onLocationChanged(Location location) {

            UpdateLocation();

        }

     

        @Override

        public void onStatusChanged(String provider, int status, Bundle extras) {

     

        }

     

        @Override

        public void onProviderEnabled(String provider) {}

     

        @Override

        public void onProviderDisabled(String provider) {}

     

        public void UpdateLocation()

        {

     

            GetPermission();

     

            coord = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

     

            if (coord != null) {

                double lattitude = coord.getLatitude();

                double longitude = coord.getLongitude();

                CoordList.setText("Latitude = " + String.format("%5.2f",lattitude) +

                        "\nLongitude = " + String.format("%5.2f",longitude));

            } else {

                CoordList.setText("No Location data available");

            };

     

        }

     

        public void GetPermission()

        {

     

            if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)

                    != PackageManager.PERMISSION_GRANTED &&

                    ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)

                            != PackageManager.PERMISSION_GRANTED){

                ActivityCompat.requestPermissions(this,

                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);

                CoordList.setText("Premission Request");

            } else {

                CoordList.setText("Already Got the Permission. So No Request");

            };

     

        }

     

     

        public void btnUpdate_Click(View v) {

            UpdateLocation();

        }

     

    }