automatically update location without restart the application - android

i am building a simple android application which require me to auto update the location. the auto update location will not only update when resuming the application but must auto update whenever the application is on. this application looks like the same with GPS system that were put inside the car. it get the exact location and always update the current location. i want to the same thing in here. i am building this application on android 2.2.
here is my code:
package com.example.map;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.widget.Toast;
public class MapActivity extends Activity implements LocationListener{
private TextView latituteField, longitudeField, accuracyField, altitudeField, bearingField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
accuracyField = (TextView) findViewById(R.id.textView1);
altitudeField = (TextView) findViewById(R.id.textView2);
bearingField = (TextView) findViewById(R.id.textView4);
// 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());
int acc = (int) (location.getAccuracy());
int alt = (int) (location.getAltitude());
int bearing = (int) (location.getBearing());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
accuracyField.setText(String.valueOf(acc));
altitudeField.setText(String.valueOf(alt));
bearingField.setText(String.valueOf(bearing));
}
#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();
}
this code it only update the location value when im resuming the application (i quit the application then go back to the application). the location will be updated at the viewtext.
i also tried to do while. like this.
if(location != null){
do{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
locationManager.requestLocationUpdates(provider, 0, 0, this);
}while(location != null);
}
else{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
im adding this to the manifest.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET" />
however, this code makes the application crash in a real phone. is there anyway to get this done?
*note: i tested all this application in my real phone and trying to achieve the current location. the textview suppose to change whenever it gets the new value of the location without pausing or quitting the application.

You have to put your location code inside an ScheduledExecutor Service:
http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
That one repeats actualization function in the background for example every 30 seconds or whatever time you specify.
Example:
scheduleTaskExecutor= Executors.newScheduledThreadPool(5);
// This schedule a task to run every 10 seconds:
scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
//add your code you would like to be executed every 10 seconds.
} catch (IOException e) {
e.printStackTrace();
}
}
}, 0, 10, TimeUnit.SECONDS);
you also might have to add a permission for coarse location.

Related

My App cannot send request to get Location

I am writhing now simple weather program. I use weather Api and must send location of phone to get weather data. As you understand I don't need precise location, so no need for GPS, noneed for ACCESS_FINE_LOCATION. What I need is - to get my location from NETWORK_PROVIDER. But here starts the problem.
At first I tried to use LocationManager and LocationListener. I enabled my WiFi and location in phone settings. Important thing that I want my application work indoor, so that no need for walking to change coordinates and LocationManager will respond. At first I check last known location.
Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
Actually, often it does not work. So I get null as location. Especiall when you turn off location in smartphone settings and after a few minutes turn it on.
OKAY, you don't have lastKnownLocation, then lets get it us. I use requestLocationUpdates() to get current location:
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
Now the magic begins... Sometime (one time in several hours OR several times in a minute) the requestLocationUpdates() works. But most of time it does not react. After many searches in internet I found Google Api, in particular FusedLocationProviderClient class. But again same story happens. But now I could understand that requestLocationUpdates() is not called.
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
I decided to put a button to see does it sends any requestLocationUpdates, but when I click button I have error.
587-673/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
To Summarize, my app simply dont send requestLocationUpdates. And I need just approximate location of my device to get city name, so no need for GPS. Please help me to solve this problem. Thanks.
You can use this class to get Current or Last Known Location if current location is currently not available.
initialize activity in your Manifest.xml
inside application tag
<activity android:name=".LocationFinder"></activity>
start this activity by calling
startActivity(new Intent(getApplicationContext(), LocationFinder.class));
finish();
Now, you can get Location in any other activity by just calling -> LocationFinder.finalAddress
Location and Internet permissions required
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
LocationFinder.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
#SuppressLint("MissingPermission")
public class LocationFinder extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private String provider;
public static String finalAddress;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoc();
}
public void getLoc() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
location = getLastKnownLocation();
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(this, "Location not available...", Toast.LENGTH_SHORT).show();
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
#SuppressLint("MissingPermission")
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex()+1;
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
finalAddress = builder.toString(); //This is the complete address.
} catch (IOException | NullPointerException e) {
// Handle IOException
}
}
#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();
}
}
After getting complete address you can use split method to get country name etc

Experimenting with Android location services

I'm trying to use a sample code (http://www.hrupin.com/2011/04/android-gps-using-how-to-get-current-location-example) that I found to see how the location services work. My code compiles, however it seems that I can't get past one part in particular when the app runs. Below is the code I am using
package com.example.gpstest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
public class MainActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {
private EditText editTextShowLocation;
private Button buttonGetLocation;
private ProgressBar progress;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextShowLocation = (EditText) findViewById(R.id.editTextShowLocation);
progress = (ProgressBar) findViewById(R.id.progressBar1);
progress.setVisibility(View.GONE);
buttonGetLocation = (Button) findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(this);
locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
}
#Override
public void onClick(View v) {
progress.setVisibility(View.VISIBLE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
AlertDialog.Builder builder = new Builder(this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please enable location providers");
builder.setPositiveButton("OK", this);
builder.setNeutralButton("Cancel", this);
builder.create().show();
progress.setVisibility(View.GONE);
}
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
}
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// This needs to stop getting the location data and save the battery power.
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
progress.setVisibility(View.GONE);
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == DialogInterface.BUTTON_NEUTRAL){
editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
}else if (which == DialogInterface.BUTTON_POSITIVE) {
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}
}
The app will not get past this if statement (I keep getting the msg "Sorry, location is not d..." that it kicks out) :
if (!gps_enabled & !network_enabled)
The original statement read:
if (!gps_enabled &amp;amp;amp;&amp;amp;amp; !network_enabled)
however I couldn't get this to compile (eclipse didn't like all the 'amps'), so I took my best guess at what it was trying to do, but I think I butchered its meaning.
if anyone could help me get this code to work, or point me in the direction of a different example so I can play with it, that would be very helpful.
edit I did add all the appropriate permmisions: access coarse location, access fine location, and Internet (just for laughs, as I'm almost positive this code doesn't need Internet)
edit changed the '&' in my code to '&&'
edit added permissions manualy and everything is now working (I orignaly used the GUI option):
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
I copied your code into a new project, added the two required permissions to the manifest, and used the && replacement Jim suggested. It works just fine on my phone.
I think you must have the permissions set incorrectly in the manifest or, probably, your phone doesn't have its GPS properly enabled for your app.
The documentation for isProviderEnabled states that "If the user has enabled this provider in the Settings menu, true is returned otherwise false is returned." The only exception I know of is that the method always returns false if your app doesn't declare the needed permissions.
If you're on an emulator or if you have your GPS disabled, that would explain it. Try getting your current location in an existing location-based application, like Google Maps.
It looks like you probably need a short-circuiting AND operator &&, rather than the
bitwise AND operator & there.

Accessing GPS is not working. Application uses network to getting location

My app doesnt want to use GPS and using network to get location instead. I checked that by analysing latitude and longtitude, they're a little bit random (like network location).
If I use another app using GPS (e.g Endomondo Sports tracker) I see characteristic mark, which means, that GPS is currently working:
When I launch my application, there's no mark at all.
I'm using following code (code by Lars Vogella, Source: http://www.vogella.com/articles/AndroidLocationAPI/article.html):
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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) {
// 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();
}
}
Of course I added permissions in AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Any ideas?
Solution:
you can use GPS instead of selecting best provider by deciding criteria.
Example, Replace:
locationManager.requestLocationUpdates(provider, 400, 1, this);
With:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1, this);
Explaination:
Depending on your application's use case, you have to choose a specific location provider
i.e. LocationManager.GPS_PROVIDER or LocationManager.NETWORK_PROVIDER
Alternatively, you can provide some input criteria such as accuracy, power requirement, monetary cost, and so on, and let Android decide a closest match location provider
// Retrieve a list of location providers that have fine accuracy, no monetary cost, etc
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setCostAllowed(false);
String providerName = locManager.getBestProvider(criteria, true);
//and then you can make location update request with selected best provider
locationManager.requestLocationUpdates(provider, 400, 1, this);
Have a look at how to use locationmanager , how to specify Criteria and how getBestProvider method works for reference

get current location in android

I have tried following code but not getting current location.
When I manual set location at emulator control then I get such location but not getting current location .I get null location.
How to get current location?
Is there any other way to get current location?
This is my code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
EditText t;
#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();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
//provider=LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
/*check provder*/boolean statusOfGPS =locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if ( statusOfGPS==true) {
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
} else {
latituteField.setText("Provider is not available");
longitudeField.setText("Provider not available");
}
}
else
{
latituteField.setText("eeeeeeeee");
longitudeField.setText("rrrrrrrrr");
}
}
/* 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);
}
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added permissions in manifest.xml as below:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
You won't get current location in emulator. You can set them through DDMS, and they will be your current location in case of a emulator.
Please, don't try to get last-known-location, most of the time it's stale and useless. Set up locationListener instead and wait for the location updates. This will get you your current location.
You may use this code to start listing for GPS updates and do something with the data you receive. It also prints messages in the log file for easy debugging. Please, note, this function does not return any results, it only starts listening to GPS. Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere.
private void getGpsData() {
locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "location change:" + location.toString());
String longitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
if( location.hasAccuracy() ) { // good enough?
// do something here with the new location data
....
//
Log.i(TAG, "GPS listener done");
locationManager.removeUpdates(this); // don't forget this to save battery
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, provider + " status:" + status);
}
public void onProviderEnabled(String provider) {
Log.i(TAG, provider + " enabled");
}
public void onProviderDisabled(String provider) {
Log.i(TAG, provider + " disabled");
}
};
Log.i(TAG,"GPS listener started");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}

Get Gps Location Using Android

I want to get latitude and Longitude from the following Android code.
location = locationManager.getLastKnownLocation(provider);
Here i am getting error location is null.
Here is the code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
} else {
latituteField.setText("Provider not available");
longitudeField.setText("Provider 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);
}
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));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added the following permisions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
But I am getting the following error:
Provider not available
If the last known location is null, it's because the phone has no last known location. If there is no location cached, you need to request an updated location, either via network, or GPS. Note that this process can take time, so must be done asynchronously.
You need to read this document:
http://developer.android.com/guide/topics/location/obtaining-user-location.html
I also recommend reading this:
http://android-developers.blogspot.co.uk/2011/06/deep-dive-into-location.html
You haven't define a valid Criteria. Define that as follows
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);//search for enabled provider
have you switched on GPS in Settings -> Location ?
why do you use (int) (location.getLatitude()) -- latitude/longitude is a float
Think you need to specify from which provider you want to receive updates.
You have two options:
GPS_PROVIDER
NETWORK_PROVIDER
You're probably missing something like this:
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
I think you may want to add the following permission as well, since I am pretty sure that the FINE relies on the COARSE...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Categories

Resources