I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}
Related
I have a service get current location of android phone as:
LocationManager locationManager;
private static int LOCATION_INTERVAL = 0;
private static float LOCATION_DISTANCE = 0;
Location mLastLocation;
Location preLocal;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
mLastLocation = location;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
// super.onCreate();
if (locationManager == null) {
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
boolean gps_enabled = false, network_enabled = false;
// SharedPreferences sh = getSharedPreferences("appShareLoc",
// MODE_PRIVATE);
// LOCATION_INTERVAL = sh.getInt("LocTime", 1);
// LOCATION_DISTANCE = sh.getInt("LocDistance", 10);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
if (gps_enabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
this);
}
if (network_enabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, this);
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (locationManager != null)
locationManager.removeUpdates(this);
}
#Override
public void onStart(Intent intent, int startId) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mLastLocation == null) {
boolean gps_enabled = false, network_enabled = false;
ty {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (network_enabled) {
mLastLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} catch (Exception ex) {
}
if (mLastLocation == null) {
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (gps_enabled) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_INTERVAL,
LOCATION_DISTANCE, this);
mLastLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
} catch (Exception ex) {
}
}
}
if (mLastLocation != null) {
//process location
}
stopSelf();
}
I only change phone in 1m But Service return 1 new Location distance previous location is 66m.
How get correct Location at first time of Service?
implement "OnMapReadyCallback"
and
try this
#Override
public void onMapReady(final GoogleMap googleMap) {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
G.customToast("Please Turn On GPS ...");
//when gps turn on , your point in map automatically send to LocationListener .
}
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Log.i("maysam", " lat " + location.getLatitude() + " lon " + location.getLongitude());
lat = location.getLatitude();
lon = location.getLongitude();
mMap = googleMap;
LatLng sydney = new LatLng(lat, lon);
mMap.addMarker(new MarkerOptions().position(sydney).title("مختصات شما"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.0f));
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location
.getLongitude(), 1);
if (addresses.size() > 0) {
String StreetName = addresses.get(0).getThoroughfare();
txtCityName.setText(StreetName);
}
} catch (Exception e) {
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
In my android app I'm retrieving user location for every 3 minutes and somehow I'm doing it in the following way.problems so far I have faced are
Whenever I'm getting location updates I'm getting multiple values at same time
Sometimes I'm getting both GPS and NETWORK provider values at a time.
I need only one value and also it should be either GPS or NETWORK Provider value,How to achieve this.
Here is my Service
public class MyService extends Service {
private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 180000;
private static final float LOCATION_DISTANCE = 0.0f;
double lati,longi;
String loc_name;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
Toast.makeText(getApplicationContext(), ""+location.getLatitude()+"==>"+location.getLongitude(), Toast.LENGTH_SHORT).show();
lati = location.getLatitude();
longi = location.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1);
if (addressList != null && addressList.size() > 0) {
{
loc_name = addressList.get(0).getAddressLine(1);
}
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeLocation());
Toast.makeText(getApplicationContext(), "" + params, Toast.LENGTH_LONG).show();
client.post("http://192.168.0.120/gpstracker/send_location.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Log.i("Status ==> ", "Sent to server");
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
mLastLocation.set(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(MyService.this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i("Service Started", "Started");
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
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;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.i(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public String composeLocation()
{
ArrayList<HashMap<String, String>> locationList = new ArrayList();
HashMap<String, String> map = new HashMap();
String parsed_lati = String.valueOf(lati);
String parsed_longi = String.valueOf(longi);
map.put("e1", "123");
map.put("lati",parsed_lati);
map.put("longi",parsed_longi);
map.put("loc_name",loc_name);
locationList.add(map);
return new GsonBuilder().create().toJson(locationList);
}
}
You should first check before getting location from both. First check if location is available through gps and if not then use network to get location.
Here is a sample class which have methods for checking location.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
Location location;
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 GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if(isGPSEnabled) {
if(location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if(locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if(locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if(location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if(location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("Turn on your GPS to find nearby helpers");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should use Criteria to request location update instead of using Provider:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, listener, null);
That way you can use only one listener and the location value can be from either GPS or NETWORK provider.
In the Android Developer guide, Google showed how to use the Google Play Services API in an activity class. What is the best way to offload the API calls into a separate class?
public class GPSresource implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private Location location; // location
private double latitude; // latitude
private double longitude; // longitude
private GoogleApiClient mGAC;
private Context mContext;
public static final String TAG = "GPSresource";
public GPSresource(Context c)
{
mContext = c;
try {
buildGoogleApiClient();
mGAC.connect();
}
catch(Exception e)
{
Log.d(TAG,e.toString());
}
}
protected synchronized void buildGoogleApiClient() {
mGAC = new GoogleApiClient.Builder(mContext)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
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;
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(mGAC);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}
The code I wrote above does not work since onConnected is never called since this is not an activity. Is there a better way to separate the GPS services from the Main Activity or is that the only option(If so, is there a reason as to why?) Perhaps making a thread in the main activity to run in the background?
Thanks!
onConnected is called, I made a mistake with reading the logs!
Here is an example :
public class LocationManager implements LocationListener {
private LocationManager locationManager;
public LocationManager()
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager.getAllProviders().contains(LocationManager.GPS_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
if (locationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
Location mobileLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null)
{
onLocationChanged(mobileLocation);
}
Location netLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (netLocation != null)
{
onLocationChanged(netLocation);
}
}
#Override
public void onLocationChanged(Location loc) {
String longitude = "Longitude: " + loc.getLongitude();
//Log.v(TAG, longitude);
String latitude = "Latitude: " + loc.getLatitude();
// Log.v(TAG, latitude);
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(loc.getLatitude(),
loc.getLongitude(), 1);
// Log.e(TAG, "addr : " + addresses.toString());
if (addresses.size() > 0)
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
String s = longitude + "\n" + latitude + "\n\nMy Current City is: " + cityName;
Log.e(TAG, "location : " + s);
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude", "disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
public void pause() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
public void destroy() {
if (locationManager != null)
{
locationManager.removeUpdates(this);
locationManager = null;
}
}
}
in
locationManager.requestLocationUpdates(provider, time, distance, locationListener);
I knew that without the priority of time and distance, If it satisfied with either condition is called a onLocationChanged()
But onLocationChanged() is not called, only called this circumstances.
1. Load the page and turns on the gps.
2. location listener catch (0,0) white gps is turned on. (onLocationChanged called)
3. gps is turn on finish.
4. The location listener is called after the time that was 'time' parameter of requestLocationUpdates(). (onLocationChanged called)
5. After... onLocationChanged is not called never..
1. If the beginning location is normal value, not (0,0). onLocationChanged is not ever call. (Even after the time specified in the parameters)
Why does not apply to the time parameters of requestLocationUpdates()?
this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
Location location;
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 *60;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS Start");
//stopUsingGPS();
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS Finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
Log.d("GPS", "lovationManager remove");
}
}
public void startCallback(){
Log.d("GPS", "startCallback()");
if(isGpsMode != isGPSOn()){
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(!GPSRegistration()){
if(isNetworkOn()){
NetworkRegistration();
}
}
}
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon : " + String.valueOf(lon));
}
public void saveLocation(){
location = null;
if (locationManager != null) {
location = getLastKnownLocation();
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
return bestLocation;
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon: "+lon);
if(!(isAvailableLocation(lat, lon))){
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}else{
if(isGPSOn()){
GPSRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}
}
if(isAvailableLocation(lat, lon)){
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
The reason I coding like this, it must be in Cordova Activity. (And the boss want it... )
+) I delete comment deliberately, because comment was Korean.. (I'm Korean)
I'm sorry that hard to understand because no comment... :(
All, thanks :)
I think you should use Service instead of BroadcastReceiver for GPS.
Self answer.
1. onlocationchanged is not called
This situation is shown when used GPS provider indoors.
When using the GPS provider at room onLocationChange () is not called. (The network provider is operating very successfully.)
So, the value of the gps provider is invalid, must be connected to the network provider.
2. The Time parameters of requestLocationUpdates() is not apply
Although not accurate, I think this is probably related to the length of time.
Because, I confirmed to be the working when by the 5 minutes(1000 * 60 * 5 ms).
It operates abnormally if shorter than the certain period.
I think Certain period is one minutes(1000 * 6 ms).
If you need, this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 5;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS start");
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startCallback(){
if(isGPSOn()){
GPSRegistration();
} else if(isNetworkOn()){
NetworkRegistration();
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon : "+lon);
if (isAvailableLocation(lat, lon)) {
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
} else {
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(isGPSOn()){
GPSRegistration();
}
}
return;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
And I've coded this code in onCreate(),
registerReceiver(gpsReceiver, new IntentFilter("actionName"));
this code in onDestroy().
unregisterReceiver(gpsReceiver);
Then, available through
startIntent(actionName).
I have created an application that stores your location in database at periodic time in Background service but, it doesn't get location. my code is...
public class LocationService extends Service {
private Double myLat, myLong;
private Location location;
private LocationManager locManager;
private LocationListener locationListener;
private boolean NETWORK_ENABLED, GPS_ENABLED, PASSIVE_ENABLED;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myLat = 0.00;
myLong = 0.00;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LocationService.this.location = location;
LocationService.this.myLat = location.getLatitude();
LocationService.this.myLong = location.getLongitude();
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
insertToDatabase();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
getMyCurrentLocation();
}
private void getMyCurrentLocation() {
location = null;
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NETWORK_ENABLED = false; GPS_ENABLED = false; PASSIVE_ENABLED = false;
NETWORK_ENABLED = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (NETWORK_ENABLED) {
Toast.makeText(getApplicationContext(), "Network Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 45 * 1000l, 1f, locationListener);
}
if (location == null) {
//setGPSOn();
GPS_ENABLED = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GPS_ENABLED) {
Toast.makeText(getApplicationContext(), "GPS Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 1f, locationListener);
}
//setGPSOff();
}
if (location == null) {
PASSIVE_ENABLED = locManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(PASSIVE_ENABLED) {
Toast.makeText(getApplicationContext(), "Passive Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0l, 1f, locationListener);
}
}
try {
location = locManager.getLastKnownLocation(locManager.getBestProvider(new Criteria(), true));
} catch(NullPointerException e) {}
if (location != null) {
myLat = location.getLatitude();
myLong = location.getLongitude();
insertToDatabase();
} else {
Location loc = null;
try {
loc = getLastKnownLocation(this);
} catch(NullPointerException e) {}
if (loc != null) {
myLat = loc.getLatitude();
myLong = loc.getLongitude();
insertToDatabase();
}
}
locManager.removeUpdates(locationListener);
}
private Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List<?> list = locationmanager.getAllProviders();
boolean i = false;
Iterator<?> iterator = list.iterator();
do {
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
else {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
}
this doesn't give me any location.... and my app is also doesn't Crash or gives any Exception.
I have properly register all permissions in Manifest file...
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
I can't find what to do?
any help will be appreciated
thanks in advance for Help...
I think your problem is that you remove the listener right away:
locManager.removeUpdates(locationListener); // comment this one out
in getMyCurrentLocation();
You should try to remove your listener in some other places.