Currently, my manifest.xml is set to following permissions for accessing location:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
My mainActivity.java file has following code for LocationManager and requestLocationUpdates():
locationmanager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationmanager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationlistener);
and #Override methods:
#Override
public void onLocationChanged(Location location) {
this.location = location;
longitude = location.getLongitude();
latitude = location.getLatitude();
}
Code gives no errors. However, the result of the above code is 0.00 for both Longitude and Latitude.
PS: Only specific sections of code are picked up from the MainActivity file. Would be ready to edit the question if more details are required.
Make sure that your locationlistener is defined as shown below. Add this class inside your mainActivity.java
class locationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
//play with location
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
switch (i) {
case LocationProvider.AVAILABLE:
Log.i("LocationListener", "GPS Available");
break;
case LocationProvider.OUT_OF_SERVICE:
Log.e("LocationListener", "GPS Out Of Service");
break;
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.w("LocationListener", "GPS Temporarily Unavailable");
break;
default:
Log.e("LocationListener", "Status changed");
}
}
#Override
public void onProviderEnabled(String s) {
Log.e("Location", "Location was enabled");
}
#Override
public void onProviderDisabled(String s) {
Log.e("Location", "Location was disabled");
}
}
Related
I am stuck with location with GPS/Network Providers. I know it is a basic question for all androiders but i am having this problem since long time.
Actually I am taking current location and inserting in database by following method on click of Option Menu.
/****
* GPS Process First of all call listener of Location then checking for GPS_PROVIDER if not
* available then check for NETWORK_PROVIDER and if its also not available then pass
* 0.00,0.00 to longitude and latitude
*/
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
int i;
for (i = 0; i < 3; i++) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListener);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
break;
} else {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
0, locationListener);
break;
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
/**
* Record Inserting Process in Database...
**/
} else {
AlertDialogManager.showAlertforSettings(AccountMenuActivity.this, "GPS Settings",
"GPS is not Enabled. Do you want to Enable?", false);
}
I am getting 0.00 latitude and longitude many times and sometimes
i got the location of other countries (China, South Africa etc...)
I dont know why it happens but after I found Stackoverflow Solution By the way finding solution since 2 days of Googling found new API of Google named FusedLocationProviderApi
That i have implemented by following some links but getting errors like:
/**
* Booleans for GPS and NETWORK is Enabled or not...
*/
boolean gpsEnabled = false;
boolean networkEnabled = false;
//exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e("TAG", "GPS Error : " + ex.getLocalizedMessage());
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e("TAG", "NetWork Error : " + ex.getLocalizedMessage());
}
Log.e("TAG", "GPS Network status : " + gpsEnabled + " : " + networkEnabled);
//don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled) {
AlertDialogManager.showAlertforSettings(VisitAcitivity.this, "GPS Settings", "GPS is not Enabled. Do you want to Enable?", false);
} else {
Log.i(TAG, "isPlayServiceAvailable" + isPlayServiceAvailable);
if(isPlayServiceAvailable) {
createLocationRequest();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mGoogleApiClient.connect();
} else {
final MyLocation.LocationResult locationResult = new MyLocation.LocationResult() {
#Override
public void gotLocation(final Location location) {
// Got the location!
runOnUiThread(new Runnable() {
#Override
public void run() {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
saveVisit();
}
});
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(VisitAcitivity.this, locationResult);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(isPlayServiceAvailable && mGoogleApiClient != null)
stopLocationUpdates();
else if (locationManager != null) {
locationManager.removeUpdates(locationListener);
Log.d("msg", "Location Listener ended...");
}
}
#Override
public void onStop() {
super.onStop();
Log.d(TAG, "onStop fired ..............");
if(mGoogleApiClient != null)
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
Log.d(TAG, "onConnected - isConnected ...............: " + mGoogleApiClient.isConnected());
startLocationUpdates();
}
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Log.d(TAG, "Location update started ..............: ");
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
Log.d(TAG, "Firing onLocationChanged..............................................");
mCurrentLocation = location;
Log.d(TAG, "UI update initiated .............");
if (null != mCurrentLocation) {
latitude = String.valueOf(mCurrentLocation.getLatitude());
longitude = String.valueOf(mCurrentLocation.getLongitude());
} else {
Log.d(TAG, "location is null ...............");
}
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
Log.d(TAG, "Location update stopped .......................");
}
In that i am managing two way to get location:
Google Play Service is available or not then get location using FusedLocation API.
Otherwise Get location using My own way (because so many device).
I had taken following permissions in My AndroidManifest.xml:
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<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" />
then also getting NULL locations :( IS THERE ANY SOLUTION for THIS PROBLEM?
Thanking you in Advance.
Try this instead: https://github.com/mcharmas/Android-ReactiveLocation
8 lines of code to get a fused location:
ReactiveLocationProvider locationProvider = new ReactiveLocationProvider(context);
locationProvider.getLastKnownLocation()
.subscribe(new Action1<Location>() {
#Override
public void call(Location location) {
doSthImportantWithObtainedLocation(location);
}
});
I am using below code to periodically check location change after some distance travelled. But onLocationChanged never called.
Android Manifiest File having permission:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity1.this,
"Provider enabled: " + provider, Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity1.this,
"Provider disabled: " + provider, Toast.LENGTH_SHORT)
.show();
}
#Override
public void onLocationChanged(Location location) {
Toast.makeText(MainActivity1.this, "onLocationChanged",
Toast.LENGTH_SHORT).show();
}
};
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0,10, locationListener);
Check your current location id null or not. & then call onlocationchanged() if its null in your activity or service.
private Location location;
if (location != null) {
mCurrentLoc.onLocationChanged(location);
}
You just need to change like:-
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
0,10, (android.location.LocationListener) this);
That's it.
I am developing a small android application in which I want to find out the user's current location by using the network provider. I tried this in following ways but it's not giving me any output :
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location
// updates
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
I gave permissions in my manifest file like this
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Is there any thing which I am missing ? Is this the correct way? Need help. Thank you...
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager gpslocationManager;
private LocationManager networklocationManager;
private LocationManager networklocationManager1;
private String provider;
private TextView gps_location;
private TextView network_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps_location = (TextView) findViewById(R.id.gps_location);
network_location = (TextView) findViewById(R.id.network_location);
networkLocation();
}
public void networkLocation() {
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
}
}
Make sure you enable Location Services in Settings! That should be the problem. It might be disabled (and this setting will usually be found in Location and Security in Settings)
Let me know if it works!
Is your network provider enabled?
boolean network_enabled;
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
ex.printStackTrace();
}
I hope this part of the code will help you extracted from vogella.
public class ShowLocationActivity 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.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#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();
}
}
I used to receive the GPS information of the code is as follows. The app error is a real phone. I think the problem of the application have to wait for Gps to receive it. How can I do this?
public class Main extends Activity {
TextView text;
Location currentLocation;
double latitude;
double longitude;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
text = (TextView)findViewById(R.id.text);
LocationManager locationManager =
(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
}
public void onStatusChanged(
String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
latitude=location.getLatitude();
longitude=location.getLongitude();
addressText.setText("Latitude: "+latitude+" \n"+"Longitude: "+longitude);
void updateLocation(Location location){
currentLocation = location;
latitude = currentLocation.getLatitude();
longitude = currentLocation.getLongitude();
}
}
I believe the official guide explains this quite well. Please take a look there: http://developer.android.com/guide/topics/location/obtaining-user-location.html
This will return null if there no last know location for the GPS.
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
You need to wait until the GSP has got a location fix for it to give you a location by calling onLocationChanged. You can add a GPS status listener to find out when this occurs.
In onCreate add:
locationManager.addGpsStatusListener(locationListener);
Add this method to locationListener:
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.d("GPSStatus", "GPS First Fix");
break;
case GpsStatus.GPS_EVENT_STARTED:
Log.d("GPSStatus", "GPS Started");
break;
case GpsStatus.GPS_EVENT_STOPPED:
Log.d("GPSStatus", "GPS Stopped");
break;
}
}
You should also check if GPS is enabled before requesting location updates.
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
I use below code to get current location of user. This code work in emulator but when I use this application in mobile it unable to give current latitude and longitude.
I uses <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> this code in android manifest file.
Please give me solution... my code is below
public class MenuPage extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menupage);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
/* Start of Class MyLocationListener for get current location of user */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location crurrentLocation)
{
Log.v("WHERE ","onLocationChanged()");
crurrentLocation.getLatitude(); // get current latitude
crurrentLocation.getLongitude(); // get current longitude
longitude=crurrentLocation.getLongitude();
latitude= crurrentLocation.getLatitude();
Log.v("WHERE ","onLocationChanged() Latitude="+latitude);
Log.v("WHERE ","onLocationChanged() Longitude="+longitude);
Toast.makeText(getApplicationContext(),"Latitud="+crurrentLocation.getLatitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Longitud="+crurrentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
send_current_location = new Send_Current_location_ToServer();
// Send current location to server
String server_message = send_current_location.sendData(userid,latitude,longitude);
// String text ="My current location is: " + "Latitud = " + crurrentLocation.getLatitude() + "Longitud = " + crurrentLocation.getLongitude();
// Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.v("WHERE ","onProviderDisabled()");
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Log.v("WHERE ","onProviderEnabled()");
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.v("WHERE ","onStatusChanged()");
}
}/* End of Class MyLocationListener */
}
There is a bug in the 2.3 emulator concerning the location services. Try changing to 2.1 to test your code.
For more info about location services, use this.
See here for the status of the bug.