Location Manager- function does'nt select provider - java

My app needs a location and when GPS provider is ON, everything working correctly = I'm getting my location. Unfortunately, when GPS is off my app can't reach Network provider even if it's on and I don't have a clue why.
After this, there's news on the screen Disabled provider Network (In this time network is avalible) and my app crashes.
Code:
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);;
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 = "Location not available";
longitudeField = "Location not available";
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider,
400, 1, this);
needGPS = true;
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
if (needGPS == false || starttime == 0)
locationManager.removeUpdates(this);
}
protected void onStop() {
super.onPause();
if (needGPS == false || starttime == 0)
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField = (String.valueOf(lat));
longitudeField = (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();
}
Why Network provider is disabled every time, even when network on my Galaxy SII is ON?

It can be a permission problem.
Open AndroidMaifest.xml and make sure you have
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />

Related

Android - How to request location update in the new API?

I was playing a bit around the new location API from google (to get latitude and longitude values):
private void getLastLocation(){
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
try {
mFusedLocationClient.getLastLocation().addOnSuccessListener(new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Toast.makeText(getApplicationContext(), String.valueOf(latitude) + "/" + String.valueOf(longitude), Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Cannot get location", Toast.LENGTH_LONG).show();
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("LocationFetch", "Error trying to get last GPS location");
e.printStackTrace();
}
});
} catch (SecurityException e){
Log.d("LocationFetch", "Permission missing");
}
}
When I first tested this code, the location was always returning null. However, after opening Instagram (which did a location update on my phone - the geo icon appeared briefly), the location was returning my relevant longitude and latitude values.
How do I request a location update on my app using the new API to prevent location from being null or retrieve very old locations? (getLastLocation() is not enough, possibly LocationRequest?)
It is worth noting that I do not want interval updates, I want for it to happen within an Android Service when invoked once.
Firstly add this implementation in your build.gradle file
implementation 'com.google.android.gms:play-services-location:11.2.0'//include the latest version of play services
After that implement, (implements LocationListener) in your activity or fragment and after that implement its function and then
call this method in your onCreate() getLocation();
and then in this function add these lines
protected void getLocation() {
if (isLocationEnabled(MainActivity.this)) {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
criteria = new Criteria();
bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();
//You can still do this if you like, you might get lucky:
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location != null) {
Log.e("TAG", "GPS is on");
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
else{
//This is what you need:
locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
}
}
else
{
//prompt user to enable location....
//.................
}
}
After that in your onLocationChanged(Location location)
add these lines of code
#Override
public void onLocationChanged(Location location) {
//Hey, a non null location! Sweet!
//remove location callback:
locationManager.removeUpdates(this);
//open the map:
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
searchNearestPlace(voice2text);
}
and you are set to go!!!!
Cheers Happy Coding
It's work for me. Based on Official docs, every 10 seconds updates the Toast and shows your location:
private FusedLocationProviderClient fusedLocationClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
#Override
protected void onResume() {
super.onResume();
startLocationUpdates();
}
private void startLocationUpdates() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// Activity#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 Activity#requestPermissions for more details.
return;
}
}
fusedLocationClient.requestLocationUpdates(locationRequest,
locationCallback,
Looper.getMainLooper());
}
#Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
private void stopLocationUpdates() {
fusedLocationClient.removeLocationUpdates(locationCallback);
}
add bellow codes to onCreate method:
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
locationRequest.setInterval(2*5000);
locationCallback=new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
if (locationResult == null) {
return;
}
for (Location location : locationResult.getLocations()) {
// if (location != null) {
String Lat = String.valueOf(location.getLatitude());
String Lon = String.valueOf(location.getLongitude());
Toast.makeText(getApplicationContext(), Lat + " - " + Lon, Toast.LENGTH_SHORT).show();
// }
}
}
};
Try this code.
In gradle
implementation 'com.google.android.gms:play-services-location:16.0.0'
In code
private void turnGPSOn() {
LocationRequest mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000)
.setFastestInterval(1 * 1000);
LocationSettingsRequest.Builder settingsBuilder = new LocationSettingsRequest.Builder()
.addLocationRequest(mLocationRequest);
settingsBuilder.setAlwaysShow(true);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient(this)
.checkLocationSettings(settingsBuilder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try {
LocationSettingsResponse response =
task.getResult(ApiException.class);
if (gps.canGetLocation()) {
lat = String.valueOf(gps.getLatitude());
lon = String.valueOf(gps.getLongitude());
}
} catch (ApiException ex) {
switch (ex.getStatusCode()) {
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException =
(ResolvableApiException) ex;
resolvableApiException
.startResolutionForResult(SignupActivity.this,
REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
}
});
}

Location Class returning empty location

I'm newcomer in Android development and I wish someone could help me.
My problem is as follow:
gradle
dependencies {
compile 'com.google.android.gms:play-services-maps:15.0.1'
compile 'com.google.android.gms:play-services-location:15.0.1'
}
MainActivity
[...]
local = (CheckBox) findViewById(R.id.local_checkbox);
local.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("DEBUG_INFO","CLICKED");
GPSTracker g = new GPSTracker(MainActivity.this);
if (((CheckBox) v).isChecked()) {
Log.v("DEBUG_INFO","CHECKED");
CheckGpsStatus();
if (GpsStatus == true) {
isLocated = true;
Location l = g.getLocation();
if ((l != null) && (isLocated == true)) {
lat = g.getLocation().getLatitude();
lon = g.getLocation().getLongitude();
Log.v("DEBUG_INFO","DEBUG_INFO:
Latitude: "+ String.valueOf(lat)+ " Longitude: "+
String.valueOf(lon));
}
else if ((l != null) && (isLocated == false)) {
lat = 0.0;
lon = 0.0;
} else {
lat = 0.0;
lon = 0.0;
}
} else {
new AlertDialog.Builder(NovaDenunciaActivity.this, R.style.AlertDialogCustom)
.setTitle("GPS TEXT!")
.setCancelable(false)
.setMessage("PLEASE SET GPS TEXT.")
.setPositiveButton("CLOSE",new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}).show();
local.toggle();
}
} else {
isLocated = false;
}
}
});
}//onCreate
public void CheckGpsStatus(){
locationManager =
(LocationManager)getSystemService(Context.LOCATION_SERVICE);
GpsStatus =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.v("CHECKBOX","MARCADO");
}
} //Code end's
GPSTracker.java
[...]
public class GPSTracker extends Activity implements LocationListener {
Context context;
/*variables*/
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public GPSTracker(Context c) {
context = c;
}
/*variables*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} //Oncreate end's?
public Location getLocation() {
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED) {
Toast.makeText(context, "No Permission Text!\nPlease allow
permissions text.", Toast.LENGTH_LONG).show();
return null;
}
//Get the location manager
locationManager = (LocationManager)
context.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.");
Log.v("DEBUG_INFO:", "Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
//latituteField.setText("Location not available");
//longitudeField.setText("Location not available");
Log.v("DEBUG_INFO:", "Latitude: not available");
Log.v("DEBUG_INFO:", "Longitude: not available");
}
return location;
}
#Override
protected void onResume() {
super.onResume();
Log.v("DEBUG_INFO:", "REQUESTING LOCATION UPDATES");
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
Log.v("DEBUG_INFO:","STOP LOCATION UPDATES");
}
#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));
Log.v("DEBUG_INFO:","Latitude: "+String.valueOf(lat));
Log.v("DEBUG_INFO:","Longitude: "+String.valueOf(lng));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(context, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(context, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
But when I click on checkbox the logcat (verbose) shows me the following:
V/DEBUG_INFO:: Latitude: not available
V/DEBUG_INFO:: Longitude: not available
The program should get latitude and longitude, if it does not exist it should call the locationManager.requestLocationUpdates(provider, 0, 0, this);
But I do not know what I'm doing wrong. Can someone help me?

Google Map Android API: .apk file works fine on my phone but not on friend's device

I am currently developing an app together with a friend of mine and I'm using the following code to acquire my current location:
public class AdressPopup extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
public static final String TAG = AdressPopup.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
TextView textViewCord;
Button okayButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.adress_finder);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// GUI items:
textViewCord = (TextView) findViewById(R.id.textViewCord);
okayButton = (Button) findViewById(R.id.button);
// Terminate window upon clicking 'okayButton':
okayButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
// How much to cover of the window..
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int) (width * .6), (int) (height * .35));
}
#Override
protected void onResume() {
super.onResume();
mGoogleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (mGoogleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
mGoogleApiClient.disconnect();
}
}
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
Locale svLocale = new Locale("sv", "SE");
//Get address based on location:
try {
Geocoder geo = new Geocoder(AdressPopup.this.getApplicationContext(), svLocale.getDefault());
List<android.location.Address> addresses;
addresses = geo.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses.isEmpty()) {
textViewCord.setText("Waiting for Location");
} else {
if (addresses.size() > 0) {
final String postalCode = addresses.get(0).getPostalCode();
final String streetName = addresses.get(0).getThoroughfare();
// final String cityName = addresses.get(0).getLocality();
StoreBackend.lookupStoreName(postalCode, new StoreBackend.Callback<String>() {
#Override
public void acceptResult(String name) {
textViewCord.append(postalCode + " (" + streetName + ") " + "\n\n" + "Din butik" + ": " + name);
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
Log.d(TAG, "Location services connected.");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//do nothing
} else if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
} else {
handleNewLocation(location);
}
// Log.d("Coordinates: ", location.getLatitude() + "," + location.getLongitude());
onLocationChanged(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Location services suspended. Please reconnect.");
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
}
We are using android studio together with bitbucket (where our repository for this project is located). This works perfectly well when I export the .apk file to my samsung galaxy s4 device. However, when my friend does the same from his android studio environment and tries this functionality on his samsung galaxy s7 (mind you, we are working with identical code) it's not working.
He is getting a null value when requesting a new location on the following line:
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
These permissions are present in the AndroidManifest.xml file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />
and the build that is being used for the play-service is '6.5.87'. Any help on the matter would be greatly appreciated.

Google maps api not placing marker at fine location

My code is supposed to find out the users location and place a marker on the map upon entering the application. My location value always equals null, and never receives a value.
if (location != null) {
lat = (int) (location.getLatitude() * 1E6);
longi = (int) (location.getLongitude() * 1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "AYO",
"Whats good yo");
CustomPinpoint custom = new CustomPinpoint(d, CampusMap.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
} else {
Toast.makeText(CampusMap.this, "Couldn't get provider",
Toast.LENGTH_SHORT).show();
}
}
I've had a relatively similar issue with a GPS RPG I was working on and here are some things I noticed:
Firstly, it can take a while for your location to initially be found, which would cause that issue since you're only checking if the location is null.
You may also want to make sure the device's location services are actually enabled before doing anything:
private boolean doLocationsCheck(){
if(!checkLocationEnabled()){
final CharSequence[] items = {"Yes", "No"};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setCancelable(false);
builder.setTitle("Location must be enabled to play this game! Would you like to enable it now?");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
final int i = item;
runOnUiThread(new Runnable() {
public void run() {
if(i == 0){
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
quit();
}
else{
quit();
}
}
});
}
}).show();
AlertDialog alert = builder.create();
return false;
}
else {
return true;
}
}
private boolean checkLocationEnabled(){
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER) || service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return enabled;
}
After I've made sure the providers are available I setup a connection like so:
private void setupLocation() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(final Location location) {
runOnUiThread(new Runnable() {
public void run() {
mLocation = location;
//Log.d(TAG, "Latitude: " + location.getLatitude() + " - Longitude: " + location.getLongitude());
saveLocation();
}
});
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
//Can set to GPS or network, whichever is available
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
The location is then set in a global variable whenever it's updated, and then saved to the preferences. This way, in the event that the providers are enabled, but are taking a while to retrieve the location, the user can still continue to use the application with their last known location that the app stored (does not apply to the first time the program is run).
I know I left out a lot there, but I figured it wasn't really necessary since it was either self-explanatory or already explained in a previous answer.
Cheers~
/*
* getting the best location using the location manager
* Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1000 Constants.MINIMUM_TIME_BETWEEN_UPDATES = 1
*/
LocationManager mLocation;
private String mBestProvider;
// in your onCreate() do the following
mLocation = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
mBestProvider = mLocation.getBestProvider(criteria, false);
Location location = mLocation.getLastKnownLocation(mBestProvider);
mLocation.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
Constants.MINIMUM_TIME_BETWEEN_UPDATES,
Constants.MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
new LocationListenerManager()
);
// and use the following locationListener inner class
private class LocationListenerManager implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
latitude = location.getLatitude();
longitude = location.getLongitude();
Toast.makeText(MapViewActivity.this, message, Toast.LENGTH_LONG).show();
Log.v("poiint=====", ""+message);
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(MapViewActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(MapViewActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
You have to initialize the locationlistener in the onstartActivity before on create so that it location obtain the location value before onCreate.

User location cannot be found

I post a question not long ago. Basically what I am trying to do is have my location manager return my longitude and latitude. My getBestProvider() method returns network, however my locationManager.getLastKnownLocation(provider) returns null. As you can see I've implemented the listener. I must have done something wrong.
Here is the code.
public class Activity1 extends Activity implements LocationListener {
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
readFile();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}#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());
System.out.println(String.valueOf(lat));
System.out.println(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, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
}
private void updateWithNewLocation(Location location){
String latLongString;TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
} else { latLongString = "No location found"; }
}

Categories

Resources