I want to start a service which will run in the background, and will show latitude and longitude every 30 to 45 seconds.
Below is my code which I'm using:
public class LocalService extends Service implements LocationListener {
private final static String TAG = "LocalService";
LocationManager lm;
public LocalService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
subscribeToLocationUpdates();
}
public void onLocationChanged(Location loc) {
Log.d(TAG, loc.toString());
Toast.makeText(getApplicationContext(), loc.getLatitude() + " - " + loc.getLongitude(), Toast.LENGTH_LONG).show();
Log.i("Location", loc.getLatitude() + " - " + loc.getLongitude());
}
public void onProviderEnabled(String s) {
}
public void onProviderDisabled(String s) {
}
public void onStatusChanged(String s, int i, Bundle b) {
}
public void subscribeToLocationUpdates() {
this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30, 0, this);
}
}
I'm calling my service like this:
startService(new Intent(TimerServiceActivity.this,
LocalService.class));
This is my manifest code for service:
<service android:name="LocalService" >
Whenever I am running this code it gives me an error message that unfortunately, TimerService has stopped.
Do you have the permissions added in your manifest?
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I instead highly recommend using this library optimized for battery usage and is rather simple to use:
http://code.google.com/p/little-fluffy-location-library/
Based on the concepts in, and some code adapted from,
android-protips-location by Reto Meier, from his blog post A Deep Dive
Into Location.
You need to subscribe to a provider first. To do this, add this in the beginning of your onCreate() method:
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);
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
Log.v(TAG, "Init");
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
Related
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 am trying to get the current location (latitude and longitude values) in my application.
I used the below code.
Problem is----------------->
When the Best provider is GPS,Location returned is null.
I learned some SO posts and I added LocationListener to my code,then it worked but when I restart my device and I run the application again,it gives the same NULL values when Provider is GPS. I don't understand why its not working now.
I also learned that Gps provider is slow in getting values,so I have to add LocationListener to solve this issue.So,I added this to my code
LocationListener locationListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, locationListener);
complete code here ----------->
public void getCurrentlocation()
{
String providers = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
Log.e("provider"," "+providers);
if(!providers.contains("gps")){
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
sendBroadcast(poke);
Log.e("your gps is","enabled");
}
LocationListener locationListener = new MyLocationListener();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 35000, 10, locationListener);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria,true);
Log.e("location provider",""+provider);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
{
System.out.println("Provider " + provider + " has been selected.");
strLatitude=String.valueOf(location.getLatitude());
strLongitude=String.valueOf(location.getLongitude());
Log.e("lattitude",strLatitude);
Log.e("logntitude",strLongitude);
latituteField.setText( strLatitude);
longitudeField.setText(strLongitude);
}
else
{
strLatitude=String.valueOf(0);
strLongitude=String.valueOf(0);
Log.e("lattitude",strLatitude);
Log.e("logntitude",strLongitude);
latituteField.setText( strLatitude);
longitudeField.setText(strLongitude);
}
}
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location location)
{
// mLattitude = location.getLatitude();
// mLongitude = location.getLongitude();
//
// Log.w("value : ",
// String.valueOf(location.getLatitude()) + String.valueOf(location.getLongitude())
// +
//
//
// context.sendBroadcast(new Intent(Constants.BRDCAST_LOCATION_UPDATED));
}
#Override
public void onProviderDisabled(String provider)
{
// Log.w("provider", provider);
}
#Override
public void onProviderEnabled(String provider)
{
// Log.w("provider", provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
// Log.w("status", String.valueOf(status));
}
}
please help
Thanks in advance
Well I tried the following code and it fetched the latitude and longitude:
public class MainActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List<String> providers = lm.getProviders(true);
/* Loop over the array backwards, and if you get an accurate location, then break out the loop*/
Location location = null;
for (int i=providers.size()-1; i>=0; i--) {
location = lm.getLastKnownLocation(providers.get(i));
if (location != null) break;
}
String Text = "My current location is: " +
"Latitud = " + location.getLatitude() +
"Longitud = " + location.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
AndroidManifest.xml:
See that the following permissions are set:
<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"/>
I am trying to create a background service that updates the current gps position. I am getting a NullPointerException at line LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
HomeActivity launches a service
startService(new Intent(getApplicationContext(), ForHire.class));
Service (ForHire) creates a TimerTask Updates
public class ForHire extends Service {
...
private Timer getUpdatesNow = new Timer();
private Updates updates = new Updates(getUpdatesNow);
#Override
public void onCreate() {
...
getUpdatesNow.schedule(updates, God.KM20TIME);
Log.v("Taxeeta", "Notification created");
}
private class Updates extends TimerTask implements LocationListener {
private Timer getUpdatesNow;
public Updates(Timer newGetUpdatesNow) {
super();
getUpdatesNow = newGetUpdatesNow;
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
God.KM20TIME, God.KM20DISTANCE, (LocationListener) this);
}
public void run() {
...
//do some cleanup
}
#Override
public void onLocationChanged(Location location) {
Log.v("Taxeeta", "Location changed");
// do a update of the current location.
}
The first issue is that I get that NullPointerException.
Second issue is that onLocationChanged is never called if I comment out LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, God.KM20TIME, God.KM20DISTANCE, (LocationListener) this); these 2 lines.
My Manifest
<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" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application ...>
...
<uses-library android:name="com.google.android.maps" />
</application>
What am I missing here ?
Edit : Values of KM20TIME = 5000 (5seconds), and KM20DISTANCE = 1 (1meter). Apart from the fix's below, I walked out of my house, got GPS enabled and walked from one corner of my balcony to the other. I noticed that my gps (LSB) changed as I walked from one corner to the other every 5 seconds.
The earliest you can call new Updates(getUpdatesNow); is inside your Service's onCreate() method. The simple reason is that getSystemService() requires a valid Context which doesn't exist before entering onCreate().
Try:
private Timer getUpdatesNow;
private Updates updates;
#Override
public void onCreate() {
...
getUpdatesNow = new Timer();
updates = new Updates(getUpdatesNow);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Toast.makeText(getBaseContext(),
"Last Location is found..",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(),
"Last Location is not found..",
Toast.LENGTH_LONG).show();
}
LocationListener locationListener = new LocationListener() {
public void onStatusChanged(String provider,
int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(),
"Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(),
"Gps Disabled", Toast.LENGTH_SHORT).show();
}
#Override
public void onLocationChanged(Location location) {
Log.i("geolocation",
"lat is : " + location.getLatitude()
+ " and " + location.getLongitude()
+ "");
Toast.makeText(getBaseContext(),
"Location is Changed..", Toast.LENGTH_LONG)
.show();
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0,
locationListener);
#Override
public void onCreate() {
new Updates(getUpdatesNow);
...
getUpdatesNow.schedule(updates, God.KM20TIME);
Log.v("Taxeeta", "Notification created");
}
I created this earlier on today, but it is not working. Location manager returns null, and I've even implemented the listener. Any ideas to the problems. thanks.
Edited:
I think this line is the problem
Location location = locationManager.getLastKnownLocation(provider);
Basically, if location is null, it will go into the else part of the if statement below it. Every time I compile the code, it will go into the else statement meaning it location is not updating.
public class Activity1 extends Activity implements LocationListener {
/** Called when the activity is first created. */
JoshTwoActivity main;
Activity2 two;
boolean checkTick = false;
String locationplace = "";
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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);
System.out.println(locationManager.isProviderEnabled(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");
}
}
/* 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());
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();
}
}
getLastKnownLocation() returns a location with the last known location fix for a provider. If the provider returns null, the provider has never had a location fix. It doesn't mean the provider is not available.
Once you call getLastKnownLocation() you should check to see if the results are accurate or recent enough for your purpose. If not you should request location updates using requestLocationUpdates().
This blog post contains everything you need to know about writing code using location providers.
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Ok my first guess is that you are not giving location fix via command line or by using eclipse DDMS perpective. If this is problem go open DDMS perpecive and give latitude and longtiude you want and send it. So location will not be null from now on if this is the problem.
The following link may help you in understanding how to use emulator in finding the location. The last section of this page has that information.
http://developer.android.com/guide/topics/location/obtaining-user-location.html
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<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"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)