I am trying to access gps location in my activity but always getting null when calling getLastKnownLocation of LocationManager class. I have added following permissions also.My GPS in enabled and I have no internet on the device.Kindly guide me what am i doing wrong
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
and also checking in code. below is my code.
public class MainActivity extends AppCompatActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
} catch (Exception e) {
e.printStackTrace();
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null){
latituteField.setText(location.getLatitude()+"");
longitudeField.setText(location.getLongitude()+"");
}else{
latituteField.setText("not found");
longitudeField.setText("not found");
}
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
implement this in your build.gradle,
implementation 'com.google.android.gms:play-services-location:17.0.0'
Try this code. It is working fine for me..
package com.example.geolocation;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
public class MainActivity extends AppCompatActivity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
private FusedLocationProviderClient fusedLocationClient;
private String TAG=MainActivity.class.getSimpleName();
LocationCallback mLocationCallback;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
2);
}
} catch (Exception e) {
e.printStackTrace();
}
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
Log.d(TAG, "onCreate: not enabled gps");
else {
LocationRequest mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(60000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationCallback = new LocationCallback() {
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
Log.d(TAG, "locationStatusCheck: onLocationResult null");
return;
}
for (Location location : locationResult.getLocations()) {
if (location != null) {
//TODO: UI updates.
Log.d(TAG, "locationStatusCheck: onLocationResult not null");
double lat = (location.getLatitude());
double lng = (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
Log.d(TAG, "latitudeField: " + latituteField);
Log.d(TAG, "longitudeField: " + longitudeField);
}
}
}
};
LocationServices.getFusedLocationProviderClient(getApplicationContext()).requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Related
************* TrackGPS.java *****************************
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.widget.Toast;
/**
* Created by ANQ on 8/8/2016.
*/
public class TrackGPS extends Service implements LocationListener {
private final Context mContext;
boolean checkGPS = false;
boolean checkNetwork = false;
boolean canGetLocation = false;
Location loc;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public TrackGPS(Context mContext) {
this.mContext = mContext;
getLocation();
}
private Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
checkGPS = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
checkNetwork = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!checkGPS && !checkNetwork) {
Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show();
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (checkNetwork) {
Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show();
try {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
catch(SecurityException e){
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (checkGPS) {
Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show();
if (loc == null) {
try {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
loc = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (loc != null) {
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
}
} catch (SecurityException e) {
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return loc;
}
public double getLongitude() {
if (loc != null) {
longitude = loc.getLongitude();
}
return longitude;
}
public double getLatitude() {
if (loc != null) {
latitude = loc.getLatitude();
}
return latitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Not Enabled");
alertDialog.setMessage("Do you wants to turn On GPS");
alertDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(TrackGPS.this);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
************* MainActivity.java ****************
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private Button b_get;
private TrackGPS gps;
double longitude;
double latitude;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_get = (Button)findViewById(R.id.get);
b_get.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
gps = new TrackGPS(MainActivity.this);
if(gps.canGetLocation()){
longitude = gps.getLongitude();
latitude = gps .getLatitude();
Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show();
}
else
{
gps.showSettingsAlert();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
gps.stopUsingGPS();
}
}
When i am running the application the latitude and longitude is showing as 0.0, i am using android marshmallow to test this application. "http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/" this is the link that i have used to create the application.
Please manage required permission for marshmallow.
First you add this permission in manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
After in your activity First declare two variable like this,
private static final int REQUEST_CODE_PERMISSION = 1;
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION;
After in onCreate method
if(Build.VERSION.SDK_INT>= 23) {
if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{mPermission,
},
REQUEST_CODE_PERMISSION);
return;
}
else
{
*here manage your code if permission already access
}
}
Here is the background service to detect current location at time interval
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
#SuppressWarnings("MissingPermission")
public class LocationBackGroundService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "LocationBackGroundService";
private static final long INTERVAL = 10;
private static final long FASTEST_INTERVAL = 10;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mCurrentLocation;
Context mCOntext;
public void LocationBackGroundService(Context mContext) {
this.mCOntext = mContext;
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
mGoogleApiClient.connect();
}
#Override
public void onCreate() {
super.onCreate();
if (!isGooglePlayServicesAvailable()) {
}
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
return false;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onConnected(Bundle bundle) {
startLocationUpdates();
}
#SuppressLint("LongLogTag")
protected void startLocationUpdates() {
PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(this,"OnConnection Suspended",Toast.LENGTH_SHORT).show();
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Toast.makeText(this,"OnConnection Failed",Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
if (null != mCurrentLocation) {
mCurrentLocation = location;
String lat = String.valueOf(mCurrentLocation.getLatitude());
String lng = String.valueOf(mCurrentLocation.getLongitude());
ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LATITUDE, lat);
ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LONGTITUDE, lng);
System.out.println("First Condition Hit");
System.out.println("Lat::-- " + lat + "\n" + "LONG::--" + lng);
}
System.out.println("Lat::-- " + location.getLatitude() + "\n" + "LONG::--" + location.getLongitude());
}
}
Put this code in seperate java file named LocationBackGroundService.java and call it in your MainActivity like this startService(new Intent(this, LocationBackGroundService.class)); and don't forget to add it in menifest like this <service android:name="LocationBackGroundService"></service>
I'm working with android studio and in a popup dialog I want that users can get their position but all I know to do is get my latitude and longitude.
This is the code
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
in the MainActivity.Can you help me?
I've added this in the manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
but it still says "Location not available".
You need the GeoCoder class to get Address from a given Lat/Long. try the following:
Geocoder geoCoder = new Geocoder(this, Locale.getDefault()); //it is Geocoder
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(latitude, longitude, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
} catch (IOException e) {}
catch (NullPointerException e) {}
Code below should work for you: (Check the inline comments regarding your code)
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
addressField = (TextView) findViewById(R.id.TextView05); //Make sure you add this to activity_main
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex();
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
String fnialAddress = builder.toString(); //This is the complete address.
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
addressField.setText(fnialAddress); //This will display the final address.
} catch (IOException e) {
// Handle IOException
} catch (NullPointerException e) {
// Handle NullPointerException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
You need to execute the Geocoder in a AsyncTask (or in a Thread not in the same ThreadGroup as the UI Thread)!
public void getCityName(final Location location, final OnGeocoderFinishedListener listener) {
new AsyncTask<Void, Integer, List<Address>>() {
#Override
protected List<Address> doInBackground(Void... arg0) {
Geocoder coder = new Geocoder(getContext(), Locale.ENGLISH);
List<Address> results = null;
try {
results = coder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
} catch (IOException e) {
// nothing
}
return results;
}
#Override
protected void onPostExecute(List<Address> results) {
if (results != null && listener != null) {
listener.onFinished(results);
}
}
}.execute();
}
With this abstract Listener
public abstract class OnGeocoderFinishedListener {
public abstract void onFinished(List<Address> results);
}
Now call the method like this:
getCityName(location, new OnGeocoderFinishedListener() {
#Override
public void onFinished(List<Address> results) {
// do something with the result
}
});
Hope this will help some of you!
You can use google api to get current location address. Check out my answer in this post go get your city.
How to get city name from latitude and longitude coordinates in Google Maps?
I'm trying to fetch geo location of the user when the app launches, i.e, during splash screen.
My approach is to get Geo location from a separate class using asynctask in main activity. I'm new to android, so I may be missing out on something. Here is the sample code which I have written to fetch user's geo location:
SplashScreenActivity.java (fetching geo location without intent-service)
package work.office;
import work.office.GeoLocationFinder.LocationResult;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
public class SplashScreenActivity extends Activity {
private static final String TAG = "SplashScreenActivity";
private ProgressDialog pd = null;
private Object data = null;
LocationResult locationResult;
Location newLocation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new GetGeoLocationAsyncTask(getApplicationContext()).execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_screen, menu);
return true;
}
private class GetGeoLocationAsyncTask extends
AsyncTask<Void, Integer, Location> {
private static final String TAG = "GetGeoLocationAsyncTask";
private Context ctx = null;
public GetGeoLocationAsyncTask(Context applicationContext) {
this.ctx = applicationContext;
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(SplashScreenActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setTitle("Loading...");
pd.setMessage("Finding your geo location... Please wait");
pd.setCancelable(Boolean.FALSE);
pd.setIndeterminate(Boolean.TRUE);
pd.setMax(100);
pd.setProgress(0);
pd.show();
super.onPreExecute();
}
#Override
protected Location doInBackground(Void... params) {
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
} else {
Log.d(TAG, "Location received is null");
}
}
};
GeoLocationFinder geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this.ctx,
locationResult);
return newLocation;
}
#Override
protected void onPostExecute(Location result) {
super.onPostExecute(result);
if (result != null) {
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ result.getLongitude() + " Latitude = "
+ result.getLatitude());
} else {
Log.d(TAG, "Coordinates are null :(");
}
pd.dismiss();
}
}
}
GeoLocationFinder.java
package work.office;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
public class GeoLocationFinder {
private static final String TAG = "GeoLocationFinder";
Timer locationTimer;
LocationManager locationManager;
Location location;
private static final int min_update_time = 20000; // in msec
private static final int min_distance_for_update = 10; // in meters
LocationResult locationResult;
boolean gps_enabled = Boolean.FALSE;
boolean network_enabled = Boolean.FALSE;
public boolean getLocation(Context ctx, LocationResult result) {
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) ctx
.getSystemService(Context.LOCATION_SERVICE);
}
try {
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception e) {
Log.d(TAG, "GPS enabled exception: " + e.getMessage());
}
try {
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception e) {
Log.d(TAG, "Network enabled exception: " + e.getMessage());
}
if (!gps_enabled && !network_enabled) {
Log.d(TAG, "You are doomed boy!!");
return Boolean.FALSE;
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, min_update_time,
min_distance_for_update, locationListenerGps);
}
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, min_update_time,
min_distance_for_update, locationListenerNetwork);
}
locationTimer = new Timer();
locationTimer.schedule(new GetLastLocation(), 20000);
return Boolean.TRUE;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "GPS provider disabled" + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "GPS provider enabled" + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "GPS status changed");
}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationTimer.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "Network provider disabled. " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "Network provider enabled. " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "Network status changed.");
}
};
private class GetLastLocation extends TimerTask {
#Override
public void run() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled) {
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if (network_enabled) {
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime()) {
locationResult.gotLocation(gps_loc);
} else {
locationResult.gotLocation(net_loc);
}
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
When i install this apk on my phone, I get this error: Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() (in SplashScreenActivity.java when in background thread I try to get location)
This question also mentions of the error but in my context I'm not able to link it. Could be because I have used SplashScreenActivity context in background thread. But how to rectify it? Also, what could be the best approach to find geo location during splash screen? Please help.
You are seriously overdoing it. The AsyncTask does not accomplish anything in this case. Here is the code simplified but still asynchronously getting the location:
package work.office;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
public class SplashScreenActivity extends Activity {
private static final String TAG = "SplashScreenActivity";
private ProgressDialog pd = null;
private Object data = null;
GeoLocationFinder.LocationResult locationResult;
Location newLocation = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
setupLocation();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splash_screen, menu);
return true;
}
private void setupLocation() {
pd = new ProgressDialog(SplashScreenActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setTitle("Loading...");
pd.setMessage("Finding your geo location... Please wait");
pd.setCancelable(Boolean.FALSE);
pd.setIndeterminate(Boolean.TRUE);
pd.setMax(100);
pd.setProgress(0);
pd.show();
GeoLocationFinder.LocationResult locationResult = new GeoLocationFinder.LocationResult() {
#Override
public void gotLocation(Location location) {
if (location != null) {
newLocation = new Location(location);
newLocation.set(location);
Log.d(TAG,
"Got coordinates, congratulations. Longitude = "
+ newLocation.getLongitude() + " Latitude = "
+ newLocation.getLatitude());
pd.dismiss();
} else {
Log.d(TAG, "Location received is null");
}
}
};
GeoLocationFinder geoLocationFinder = new GeoLocationFinder();
geoLocationFinder.getLocation(this,
locationResult);
}
}
When running the application in android 2.2 the GPS is searching for location but doesn't show any location. This application is working perfectly in ICS version. What will be the reason?
Thanks in advance.
This is the complete code :-
package com.example.gps;
import android.app.Activity;
import android.location.Criteria;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Location;
import android.os.Bundle;
import android.view.Window;
import android.widget.TextView;
import java.io.IOException;
public class GPSmap extends Activity implements LocationListener {
public String mLatLongString = "";
private String mBest;
private TextView myLocationText;
LocationManager mLocManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_LEFT_ICON);
setContentView(R.layout.activity_gpsmap);
myLocationText = (TextView) findViewById(R.id.myLocationText);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
R.drawable.ic_launcher);
mLocManager = (LocationManager) getSystemService(LOCATION_SERVICE);
try {
Criteria mCriteria = new Criteria();
mCriteria.setAccuracy(Criteria.ACCURACY_FINE);
mBest = mLocManager.getBestProvider(mCriteria, true);
if (mLocManager.isProviderEnabled(mBest)) {
}
} catch (NullPointerException e) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
myLocationText.setText("\n\nGPS Tracking: Disabled.");
}
}
private void updateWithNewLocation(Location mLocation) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
if (mLocation != null) {
double mLatitude = mLocation.getLatitude();
double mLongitude = mLocation.getLongitude();
double mLatitudeFormatted = (double) Math.round(mLatitude * 100000) / 100000;
double mLongitudeFormatted = (double) Math
.round(mLongitude * 100000) / 100000;
mLatLongString = mLatitudeFormatted + ", " + mLongitudeFormatted;
myLocationText.setText(mLatLongString);
} else {
mLatLongString = "\n\nNo Location Found.";
myLocationText.setText(mLatLongString);
}
}
/** Function to listen to location change */
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
protected void onResume() {
try {
super.onResume();
mLocManager.removeUpdates((android.location.LocationListener) this);
mLocManager.requestLocationUpdates(mBest, 60000L, 0.0f, this);
} catch (NullPointerException e) {
myLocationText = (TextView) findViewById(R.id.myLocationText);
myLocationText.setText("\n\nGPS Tracking: Disabled.");
}
}
}
I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 35000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.