ANDROID: get current GPS location never call "onLocationChanged" - android

trying to get current Longitude and Latitude.
CODE:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new myLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, locationListener);
}
class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
tvLang.setText("");
Toast.makeText(getBaseContext(), "Location changed: Lat: " + loc.getLatitude() + " Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
but when I run it on my LG G2 - it never get into the "onLocationChanged" function.
the GPS is On, i can find myself in Google Maps.
tried to restart the phone few times.
what I'm doing wrong?

Related

Check if user disable GPS in settings in android

There is any solution to check if user disable GPS in settings?
I open my app, open top toolbar of android system, disable GPS and close this toolbar. In this moment I want to app check if status of GPS was changed.
I use check if GPS is active in onResume(), but this solution works only when user enable GPS, when disable onResume() is not called.
Any ideas?
Edit:
This is may class:
public class PrivacyActivity extends BaseActivity implements GpsStatus.Listener, LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Toast.makeText(this, "ads", Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(this, "ads1", Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
}
and when I disable gps I didn't see toast.
You can use the LocationListener class
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Log.i("Example", "GPS is ON");
}
public void onProviderDisabled(String provider) {
Log.i("Example", "GPS is OFF");
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You can get more info in http://developer.android.com/guide/topics/location/strategies.html
Reference the locationListener first.
LocationListener locationListener;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng myPlace = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(myPlace).title("me"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPlace));
mMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
};
onProviderDisabled method will be fired if the user has disabled GPS from settings.
The intent inside the method will take the user to location settings directly.
Tested and works fine.

Disable location updates from GPS

UPDATED QUESTION - STILL NOT WORKING
I've changed the code.
Now, deactivateAlerts and activateAlerts are in the MainActivity.
Now, inside activateAlerts(), I'm instantiating a GPSListener for the GPS Provider:
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
gpsListener = new GPSListener(getApplicationContext());
} else if
Where the GPSListener is this:
public class GPSListener implements LocationListener {
private Context mCtx;
private Location cLoc;
private LocationManager mLocMan;
public GPSListener (Context ctx){
mCtx = ctx;
mLocMan = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
mLocMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
public Location getLocation()
{
cLoc = mLocMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
return cLoc;
}
public void stop()
{
mLocMan.removeUpdates(GPSListener.this);
}
#Override
public void onLocationChanged(Location location) {
Log.i("UPDATING", "updating location");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
With the deactiveAlerts() function, I execute the instruction to remove the GPS updates:
if(gpsListener!=null){
gpsListener.stop();
}
But the GPS is not stopping yet =(
What is the problem now?
ORIGINAL QUESTION
The user can activate or deactivate location updates.
If the location updates are activated, it works ok, but when the location updates are deactivated, the GPS is still waiting for updates (and the icon appears on the action bar).
The code is that:
public class Alerts extends Fragment {
MyLocationListener myLocationListener = null;
...
public void activateAlerts() {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
} else {
locationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
Utils.MINIMUM_TIME_BETWEEN_UPDATE,
Utils.MINIMUM_DISTANCECHANGE_FOR_UPDATE,
myLocationListener
);
}
}
});
...
}
public void deactivateAlerts() {
...
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
if(myLocationListener != null) {
locationManager.removeUpdates(myLocationListener);
myLocationListener = null;
}
...
}
public class MyLocationListener implements android.location.LocationListener {
public void onLocationChanged(Location location) {
Log.i("UPDATING", "updating location");
}
public void onStatusChanged(String s, int i, Bundle b) {
Log.v("LocationListener", "onStatusChanged");
}
public void onProviderDisabled(String s) {
Log.v("LocationListener", "onProviderDisabled");
}
public void onProviderEnabled(String s) {
Log.v("LocationListener", "onProviderEnabled");
}
}
What is the problem?
I've read this posts:
Post1
Post2
Post3
Post4

Android LocationListener not called

I'm making an app that sends the present location through sms. But the location listener method is not called. It says:
method LocationListener is never called
Here's my code :
public class MainActivity2 extends Activity {
LocationManager lm;
LocationListener locationListener;
private void LocationListener(Context context) {
lm = (LocationManager)
context.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
60000,
1000,
locationListener);
}
private class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
String Uri = "http://maps.google.com/maps?saddr=" + loc.getLatitude() + "," + loc.getLongitude();
SmsManager smsManager = SmsManager.getDefault();
StringBuffer smsBody = new StringBuffer();
smsBody.append(Uri);
smsManager.sendTextMessage("+91847690****", null, smsBody.toString(), null, null);
lm.removeUpdates(locationListener);
}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
It looks like the confusion is that you have created a method in your MainActivity2 class that is called LocationListener(). This is not good, since you shouldn't have a method with the same name as the LocationListener class.
Just rename the method, and since this method is part of your Activity, you don't need to pass in a Context:
private void setUpLocationListener() {
lm = (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new MyLocationListener();
lm.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
60000,
1000,
locationListener);
}
Then, just call the method from onCreate():
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setUpLocationListener();
}

getting geolocation after 20 seconds

i am making an android app using geo-location in android. i am using the location manager for getting the geo-location coordinates.
locationManager.requestLocationUpdates(provider, 0, 0, this);
Location location = locationManager.getLastKnownLocation(provider);
and using the postDelayed() function for continuously called the getLastKnownLocation() for the geo-location. and set the interval timing 1000 (1 sec). but i get the response after 20 seconds.
Can any body explain me why it happens. i am new in android.
Note that you shouldn't be calling getLastKnownLocation() every second if you have a Location Listener set up (which it looks like you do). Just use the latest values given in the onLocationChanged() callback.
This code works for me, it registers a Location Listener, which updates the lat/lon member variables, and then the Runnable runs with an initial interval of one second, and then every five seconds (5000 milliseconds) and displays the most current location value.
I put in a Toast to make sure that the Runnable is being run every 5 seconds by handler.postDelayed().
Here is the full Activity code:
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity implements LocationListener {
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
TextView lat;
TextView lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
handler.postDelayed(runLocation, 1000);
}
public Runnable runLocation = new Runnable(){
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Edit:
As an alternative, you could take out the use of postDelayed(), and just use the onLocationChanged() events.
In the example below, I used both NETWORK_PROVIDER and GPS_PROVIDER.
This is needed in the AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Here is the modified code, which registers the Activity as a Location Listener for both Network location callbacks and GPS location callbacks, with a minimum time interval of one second. Note that events can come in at a greater interval than one second, but with the GPS location enabled, I saw them coming in every second (it was taking longer with only Network location enabled).
public class MainActivity extends ActionBarActivity implements LocationListener {
LocationManager locationManager;
Handler handler;
Location location;
double latitude;
double longitude;
TextView lat;
TextView lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler();
lat = (TextView) findViewById(R.id.latitudeTextView);
lon = (TextView) findViewById(R.id.longitudeTextView);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null){
latitude = location.getLatitude();
longitude = location.getLongitude();
}
//handler.postDelayed(runLocation, 1000);
}
/*
public Runnable runLocation = new Runnable(){
#Override
public void run() {
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();
MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
}
};
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
lat.setText(String.valueOf(latitude));
lon.setText(String.valueOf(longitude));
Toast.makeText(MainActivity.this, "location changed: " + latitude + " " + longitude, Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
use google map api v2
example
public class MapActivity extends FragmentActivity {
protected GoogleMap map;
protected LatLng start;
protected LatLng end;
TextView tvDistance,tvTime;
CameraPosition mCameraPosition;
// LatLng currentLocation ;
Context context;
public static boolean loadMapChk = false;
double getlatitute, getlongitute;
String addressGeo;
/**
* This activity loads a map and then displays the route and pushpins on it.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
context = this;
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
getlatitute = bundle.getDouble("getlatitute");
getlongitute = bundle.getDouble("getlongitute");
addressGeo = bundle.getString("addressGeo");
}
tvDistance = (TextView) findViewById(R.id.tvDistance);
tvTime = (TextView) findViewById(R.id.tvTime);
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
map = fm.getMap();
map.setMyLocationEnabled(true);
map.setOnMyLocationChangeListener(myLocationChangeListener);
}
private GoogleMap.OnMyLocationChangeListener myLocationChangeListener = new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange (Location location) {
LatLng loc = new LatLng (location.getLatitude(), location.getLongitude());
// Toast.makeText(getApplicationContext(),"location.getLongitude()>>>>>>>"+location.getLongitude(),Toast.LENGTH_LONG).show();
// map.animateCamera(CameraUpdateFactory.newLatLngZoom(loc, 16.0f));
Bitmap bitmapicon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.start_blue);
map.addMarker(new MarkerOptions().position(
new LatLng(location.getLatitude(), location.getLongitude())).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(bitmapicon)));
if (!loadMapChk)
{
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(), location.getLongitude()), 12.5f), 4000, null);
loadMapChk = true;
}
start = new LatLng(location.getLatitude(), location.getLongitude());
end = new LatLng(getlatitute, getlongitute);
Bitmap bitmapiconEnd = BitmapFactory.decodeResource(context.getResources(),
R.drawable.end_green);
map.addMarker(new MarkerOptions().position(
new LatLng(getlatitute, getlongitute)).title(addressGeo).icon(BitmapDescriptorFactory.fromBitmap(bitmapiconEnd)));
Routing routing = new Routing(Routing.TravelMode.DRIVING);
routing.registerListener(routingListener);
routing.execute(start, end);
}
};
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
loadMapChk = false;
}
public RoutingListener routingListener = new RoutingListener() {
#Override
public void onRoutingSuccess(PolylineOptions mPolyOptions, Route route) {
PolylineOptions polyOptions = new PolylineOptions();
polyOptions.color(Color.CYAN);
polyOptions.width(8);
polyOptions.addAll(mPolyOptions.getPoints());
tvDistance.setText("Distance : "+route.getDistanceText());
tvTime.setText("Time : "+route.getDurationText());
// Toast.makeText(getApplicationContext(), "Distance : "+route.getDistanceText()+" & Time = "+route.getDurationText(),6).show();
map.addPolyline(polyOptions);
// Start marker
MarkerOptions options = new MarkerOptions();
// End marker
options = new MarkerOptions();
options.position(end);
options.icon(BitmapDescriptorFactory.fromResource(R.drawable.end_green));
map.addMarker(options);
}
#Override
public void onRoutingStart() {
// TODO Auto-generated method stub
}
#Override
public void onRoutingFailure() {
// TODO Auto-generated method stub
}
};
}
Use timer handeller to implement delay.
Total time= Time delay+ Server response
You might be facing problem because of that

LocationManager doesn't update a location

There is the following code for getting current location:
final LocationManager manager=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener listener=new LocationListener() {
#Override
public void onLocationChanged(Location location) {
manager.removeUpdates(this);
Toast.makeText(MainActivity.this, "2", Toast.LENGTH_LONG).show();
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(MainActivity.this, LOCATION_IS_NULL_MESSAGE, Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
manager.removeUpdates(this);
String newProvider=provider.equals(LocationManager.GPS_PROVIDER) ? LocationManager.NETWORK_PROVIDER : null;
if (newProvider==null) {
Toast.makeText(MainActivity.this, LOCATION_PROVIDERS_ARE_DISABLED_MESSAGE, Toast.LENGTH_LONG).show();
}
else {
manager.requestLocationUpdates(newProvider, 0, 0, this);
}
}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
String provider=manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ? LocationManager.GPS_PROVIDER :
LocationManager.NETWORK_PROVIDER;
Location location=manager.getLastKnownLocation(provider);
if (location!=null) {
doSomeAction();
}
else {
Toast.makeText(this, "1", Toast.LENGTH_LONG).show();
manager.requestLocationUpdates(provider, 0, 0, listener);
}
I see toast "1" each time, but I've never seen "2" toast, therefore my location isn't be updated. Please, tell me, I need to get my current location - how can I fix my problem? I use network location provider.
Did you actually attach the listener? With out attaching the listener its code is useless, but furthermore afaik: If the LocationManager has no Listener attached it will not update any location.
Try like this :
public class Locato extends Activity implements LocationListener {
LocationManager locman;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.idlayout);
locman = (LocatonManager) getSystemService(Context.LOCATION_SERVICE);
}
public void onStatusChanged(String pr, int s, Bundle a) {}
#Override
public void onProviderDisabled(String provider) {
Log.d("MyApp", "Provider disabled : " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.d("MyApp", "Provider enabled : " + provider);
}
#Override
public void onLocationChanged(Location location) {
// do something
}
You must also add permissions to manifest : access coarse location and access fine location

Categories

Resources