0

I am newbie to native android development. For understanding it, i am developing an app which will show me gps location of me. For this i searched on the internet and found two tutorials.

I am following Link1, and followed each step in it, Bellow is the code which I have written.

GPSTracker.java

import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.provider.Settings;


public class GPSTracker extends Service implements LocationListener {

private final Context mContext;

// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;

boolean canGetLocation = false;

Location location; // location
double latitude; // latitude
double longitude; // longitude

// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 5 meters

// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 10000; // 10 seconds

// Declaring a Location Manager
protected LocationManager locationManager;

public GPSTracker(Context mContext) {
    this.mContext = mContext;
}

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            Log.i("", "Network Value: " + isNetworkEnabled);
            Log.i("", "GPS Value: " + isGPSEnabled);
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            // First get location from Network Provider
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,
                        this
                );
                Log.d("Network", "Network");
                if (locationManager != null) {

                    location = locationManager

                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

                    if (location != null) {

                        latitude = location.getLatitude();

                        longitude = location.getLongitude();

                    }

                }

   /*                    if (ActivityCompat.checkSelfPermission(this,  Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED  && ActivityCompat.checkSelfPermission(this,  Manifest.permission.ACCESS_COARSE_LOCATION) !=  PackageManager.PERMISSION_GRANTED) {
    //
    // TODO: Consider calling
   //
  // ActivityCompat#requestPermissions
 //
 // here to request the missing permissions, and then overriding

 // public void onRequestPermissionsResult(int requestCode, String[] permissions,
//
// int[] grantResults)
//
// to handle the case where the user grants the permission. See the documentation

// for ActivityCompat#requestPermissions for more details.

                           return location;

                     }*/
            }
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
        }
    } catch (Exception e) {

        e.printStackTrace();
        Log.i("", "Exception " + e);

    }
    return location;
}

/**
 * Stop using GPS listener
 * Calling this function will stop using GPS in your app
 * */
public void stopUsingGPS() {
    if (locationManager != null) {
        /*if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }*/
        locationManager.removeUpdates(GPSTracker.this);
    }}

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
    }

    // return longitude
    return longitude;
}

/**
 * Function to check GPS/wifi enabled
 * @return boolean
 * */
public boolean canGetLocation() {
    return this.canGetLocation;
}

/**
 * Function to show settings alert dialog
 * On pressing Settings button will lauch Settings Options
 * */
public void showSettingsAlert(){
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

    // Setting Dialog Title
    alertDialog.setTitle("GPS is settings");

    // Setting Dialog Message
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

    // On pressing Settings button
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog,int which) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            mContext.startActivity(intent);
        }
    });

    // on pressing cancel button
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        }
    });

    // Showing Alert Message
    alertDialog.show();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onLocationChanged(Location location) {

}

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

}

@Override
public void onProviderEnabled(String provider) {

}

@Override
public void onProviderDisabled(String provider) {

}}

Bellow is my main activity code

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {
Button btnShowLocation;
TextView textShowLocation;
// GPSTracker class
GPSTracker gps;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
    // show location button click event
    btnShowLocation.setOnClickListener(new View.OnClickListener(){


        @Override
        public void onClick(View v) {
            // create class object
            gps = new GPSTracker(MainActivity.this);
            // need to make canGetLocation flag true by calling below method as per your code.
            **gps.getLocation()**
            // check if GPS enabled
            if(gps.canGetLocation()){
                double latitude = gps.getLatitude();
                double longitude = gps.getLongitude();
                textShowLocation.append("Your Location is - \nLat: " + latitude+ "\nLong: " + longitude);
            }
            else
            {
                // can't get location
                // GPS or Network is not enabled
                // Ask user to enable GPS/network in settings
                gps.showSettingsAlert();
            }
        }
    });



}

Update 1

Below is my manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.accurat.tracker">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    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>

While running the app into my device, whenever i click the show location button it always redirect me to the else part i.e. gps.showSettingsAlert(); run. No matter if 'GPS' of my device is on it still not showing me the location. Moreover, comment or un-comment the permission check is not helping.

Any help would be highly appreciated:

10
  • 2
    Did you set the permissions correctly on Manifest ? Commented Jan 25, 2017 at 5:40
  • @ThisaruGuruge kindly see the update 1 Commented Jan 25, 2017 at 5:42
  • Did you tried with multiple devices? Commented Jan 25, 2017 at 5:45
  • 1
    @faisal1208 tell us the complete details which device you are testing on .. its API level and code block from which to which its going to .. debug and check the if else condition the values you are getting, then only we can help. Commented Jan 25, 2017 at 5:59
  • 1
    as I can see the code the minimum sdk is android:minSdkVersion="8" why are you lying to us? Commented Jan 25, 2017 at 6:59

3 Answers 3

1

you need to call getLocation(); method in the constructor:

 public GPSTracker(Context mContext) {
    this.mContext = mContext;
    getLocation();
}

in your GPSTracker class add this code:

 @Override
public void onLocationChanged(Location location) {
    this.location = location;
    getLatitude();
    getLongitude();
}

Also the class u are using has some problems: see this blog http://gabesechansoftware.com/location-tracking/

you can use FusedLocationApi

here is an example:http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html

Sign up to request clarification or add additional context in comments.

6 Comments

By implementing your logic, now on button click my app app crashes and gives me the message Unfortunately, Tracker has stopped
it's giving me this error in logcat FATAL EXCEPTION: main Process: com.example.accurat.tracker, PID: 10668 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference
you need to instantiate textShowLocation first using findviewByID from layout
Now it's running but it's showing me lat, long 0,0 :|
try changing MIN_DISTANCE_CHANGE_FOR_UPDATES and MIN_TIME_BW_UPDATES to 0 , 0 and check the edit
|
0

if you are using 5.0+ version then add

< uses-feature android:name="android.hardware.location.gps" />

to your manifest. and if you are testing on marshmallow you have to add

int REQUEST_CODE_PERMISSION=101;
    void allowGPS() {
            try {
                if (Build.VERSION.SDK_INT >= 23 {
                    Log.i("*******", "check build permission");
                    try {
                        if (getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
                                // permission wasn't granted
                            } else {
                                ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_PERMISSION);
                            }
                        }
                    } catch (Exception ae) {

                    }
                }
            } catch (Exception ae) {
                ae.printStackTrace();
            }
        }



 @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == REQUEST_CODE_PERMISSION) {
            if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted
            } else {
                // permission wasn't granted
            }
        }
    }

Comments

0

GPSTracker is a service class. You have to start the service to get location. Now else condition is showing because location is not fetched yet. You can start service by startService(new Intent(context, GPSTracker.class));

Also change your button click code by this

 LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
        Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
    }else{
        showGPSDisabledAlertToUser();
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.