Im new to android development and i understand the android activity life cycle. Please see the following code.
public class MyTest extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
cont = getApplicationContext();
final MyLocation my_loc = new MyLocation ();
my_loc.initialize(cont);
myMethod();
}
Public void myMethod()
{
//here when I retrieve the values, it always shows 0.0.
}
}
public class MyLocation implements LocationListener {
public double user_lat;
public double user_lng;
private LocationManager locationManager;
private Context ctx;
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
user_lat = location.getLatitude();
user_lng = location.getLongitude();
//here i save the values for constands to use in myMethod
}
}
public void initialize(Context context) {
this.ctx = context;
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, this);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
}
}
Why is it that i cannot initialize GPS and retrieve long and lat values in the same activity?
LocationClient is the new way of getting GPS. Watch video for complete details on the recent update.
Note that the LocationManager way of doing things is buggy, since there is need to add a lot of code for GPS and NETWORK provider. The new way (internal to Google referred to as the Fused Location Provider) works with sensors to reduce battery consumption big time. Also reduces the need for complex API's and stage wise selection of the best provider. Its just 2-3 lines of code and you are done.
With many Samsung phones (Y model including) though there is a specific issue that most of the times they don't return location at all. So you need to kick start that phone to return the GPS. To do that you can use
HomeScreen.getLocationManager().requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(final Location location) {
}
});
And then call your locationClient.getLastLocation api. As in put the code above, just before your LocationClient.getLastLocation or LocationManager.getLastKnownLocation call.
Mind you Samsung is the highly customized android open source product. Google cannot respond to samsung related bugs, and Samsung does not have any android developer related support.
Edit : Watch the video, trust me, without knowing what LocationClient gives you, you wont appreciate the change. You will also learn about GeoFenceing.
In order to your location question, I would suggest you another new way of retrieving locations.
Check this out: google play util
The code below is just a snippet, not fully ;). You dont need to handle gps/network providers anymore. It handles for you, which one is the best and returns a location.
LocationClient mLocationClient = new LocationClient(...)
mLocationClient.connect();
...
onConnected(Bundle ...){
LocationRequest request = LocationRequest.create();
request.setNumUpdates(1);
...
mLocationClient.requestLocationUpdates(request, new LocationListener....)
....
}
I made one service for that. It is easy for get Longitude / Latitude using it.
Copy/paste this class in your project.
package com.sample;
import com.sample.globalconstant;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyServiceGPS extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude());
globalconstant.lat = location.getLatitude();
globalconstant.lon = location.getLongitude();
Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show();
mLastLocation.set(location);
}
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
Copy this code in your Activity when you want to start:
startService(new Intent(this,MyServiceGPS.class));
Create one class globalconstant:
public class globalconstant { public static double lat, lon; }
when you want to current latitude and longitude in your project only write this globalconstant.lat ,globalconstant.lon
Add uses-permission in Manifest
Related
I want to get latitude and longitude by a service that do in background and when the app is not run.
Is there someone who guides me with an example ?
The most important thing is that when the program is completely closed, the service will work correctly and show the latitude and longitude.
My request is very similar to the following link.
getting latitude and longitude using gps every 10 minute in background android
None of the apps I was looking for in the background or when the program was closed was not properly executed.
Thanks
Try this code to get location updates periodically in background service
Change LOCATION_INTERVAL &
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
public class MyLocationService extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
/*
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
*/
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.PASSIVE_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[0]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
/*try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
LOCATION_INTERVAL,
LOCATION_DISTANCE,
mLocationListeners[1]
);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}*/
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: "+ LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
I am creating app which updates the location in background using service. Now it is done by gps and network provider both. But I want to get last location using network provider only because gps consumes lot of battery. I got code online which I modified is as below
public class MyLocationServiceOne extends Service {
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 0;//MIN_TIME_BW_UPDATES 1 Minute
private static final float LOCATION_DISTANCE = 0f;//MIN_DISTANCE_CHANGE_FOR_UPDATES
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
Log.e(TAG, "Location : " + location.getLatitude()+" , "+
location.getLongitude());
mLastLocation.set(location);
double lati=location.getLatitude();
double longi=location.getLongitude();
if(String.valueOf(lati)!=null&&String.valueOf(longi)!=null) {
Toast.makeText(MyLocationServiceOne.this, String.valueOf(lati)+String.valueOf(longi), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
//new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
final LocationManager manager = (LocationManager) getSystemService( Context.LOCATION_SERVICE );
if ( !manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
//buildAlertMessageNoGps();
}
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
/*try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}*/
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
But it gives gps coordinates only when gps is on.
Thanks for any help
Getting location through gps is painful to user since it consumes a lot of battery as you indicated above. You can select your provider too, that is what is source of getting location, is it network or it is gps. These all depends on your location needs and some other logics of app. well to cut short it, I must say you need to learn location strategies. This will give you better understanding. Please look this here.
I will recommend you to use google's fused location API. This give you better control on locations, and the best part of this API is that it is battery efficient and it is really fast and reliable. here is a link if you want to learn about it. and for some more code snippts and helping material see this, this and this one is so advance also if you are using kotlin it has its demo code.
Ask if there is any confusion.
I am developing a Tracking app, which keeps tracks of the user by getting his current location for every 3 secs. I am able to fetch the lat long values when the screen is on. but when the screen sleeps. i am unable to fetch the datas.
CODE:
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude());
Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
Log.d("onLocationChanged", "Exit");
Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
}
The above given onLocationChanged method fetches the lat lon values for every 3 seconds. What should i do to make this method run even if the screen sleeps. I have read about Wakelock dont know how to implement it, any help will be appreciated. Thanks in advance.
Note: The app runs perfectly when multi tasking is done,
use job scheduler to get location after every 3 seconds it also works when screen sleep https://developer.android.com/reference/android/app/job/JobScheduler.html
You need to make use of Service to get location updates even if screen sleep or your app is not open.
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class MyLocationService extends Service
{
private static final String TAG = "MyLocationService";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 3000;
private static final float LOCATION_DISTANCE = 10f;
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
// create LocationListener class to get location updates
private class LocationListener implements android.location.LocationListener
{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
}
Add MyLocationService into your AndroidManifest.xml also:
<service android:name=".MyLocationService" android:process=":mylocation_service" />
Don't forgot to add below two permissions in your AndroidManifest.xml file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Start Service from an activity:
You can start a service from an activity or other application component by passing an Intent (specifying the service to start) to startService(). The Android system calls the service's onStartCommand() method and passes it the Intent.
Intent intent = new Intent(this, MyLocationService.class);
startService(intent);
Update:
You need to hold partial wake lock to run service even after device screen off.
If you hold a partial wake lock, the CPU will continue to run, regardless of any display timeouts or the state of the screen and even after the user presses the power button.
To acquire wake lock:
PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
WakeLock wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
wakeLock.acquire();
To release it:
wakeLock.release();
Try using Service or JobScheduler and implement LocationListener
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if (mCurrLocationMarker != null)
{
mCurrLocationMarker.remove();
}
latitude = location.getLatitude();
longitude = location.getLongitude();
latLngcurrent = new LatLng(location.getLatitude(),location.getLongitude());
Toast.makeText(context,String.valueOf(latitude)+" "+String.valueOf(longitude), Toast.LENGTH_LONG).show();
Log.d("onLocationChanged", String.format("latitude:%.3f longitude:%.3f",latitude,longitude));
Log.d("onLocationChanged", "Exit");
Toast.makeText(this, "exiting LocationChanged ", Toast.LENGTH_SHORT).show();
}
I had developed a real-time GPS location tracking system in which the mobile devices integrated with GPS device send location information to web server obtained at database and it is being plotted in Google map by calling the function to plot GPS data in map periodically as function is called repeatedly over specific time interval.
On the user end we can watch the location update like the plotters blinking and changing the location in Google map.
Is there any other best method to show real-time GPS location on Google map?
Any method to make the plotters move without blinking, like continuously flowing through map?
Any piece of code is appreciated & thanks in advance.
I suggest you to store the location history in database, make it short duration and lets call it Location Frame. Now you have a from and to coordinate positions to move your plotters in the map. update the frame by setting a frequency in which the new frame can be applied when plotter have approached the destination of last frame. Build pragram on this logic. hope it helped :)
I implemented this code into a service and it only get the cordinates... they are never rendered into any map....
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
sLat = Double.toString(location.getLatitude());
sLong = Double.toString(location.getLongitude());
Speed = Double.toString(location.getSpeed());
sAlt = Double.toString(location.getAltitude());
sTime = Double.toString(location.getTime());
Log.e(TAG, "onLocationChanged: " + location + localTime);
mLastLocation.set(location);
}
#Override
public void onProviderDisabled(String provider) {
Log.e(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
TelephonyManager mngr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
IMEI = mngr.getDeviceId();
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
I have tried the below program. It is working in eclipse -> if u give lattitude and longitude value through ddms means it displayed in emulator as current position....
but its not detecting current position in android phone.
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
Date today = new Date();
Timestamp currentTimeStamp = new Timestamp(today.getTime());
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPS){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: "+
"\n Latitude: "+ location.getLatitude() +
"\n Longitude: " + location.getLongitude() +
"\n Accuracy: " + location.getAccuracy() +
"\n CurrentTimeStamp "+ currentTimeStamp;
Toast.makeText(MainActivity.this,str,Toast.LENGTH_SHORT).show();
tv.append(str);
}
else
{
String s1="GPS activation in process";
Toast.makeText(MainActivity.this,s1,Toast.LENGTH_SHORT).show();
/*alert.setTitle("gps");
alert.setMessage("GPS activation in progress,\n Please click after few second.");
alert.setPositiveButton("OK", null);
alert.show();*/
}
}
else
{
String s2="Enable Gps";
Toast.makeText(MainActivity.this,s2,Toast.LENGTH_SHORT).show();
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
I made one service for that. It is easy for get Longitude / Latitude using it.
Copy/paste this class in your project.
package com.sample;
import com.sample.globalconstant;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyServiceGPS extends Service
{
private static final String TAG = "BOOMBOOMTESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f;
private class LocationListener implements android.location.LocationListener{
Location mLastLocation;
public LocationListener(String provider)
{
Log.e(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
public void onLocationChanged(Location location)
{
Log.e(TAG, "onLocationChanged: " + location.getLatitude() +"....."+ location.getLongitude());
globalconstant.lat = location.getLatitude();
globalconstant.lon = location.getLongitude();
Toast.makeText(getApplicationContext(), location.getLatitude() +"....."+ location.getLongitude(), 1000).show();
mLastLocation.set(location);
}
public void onProviderDisabled(String provider)
{
Log.e(TAG, "onProviderDisabled: " + provider);
}
public void onProviderEnabled(String provider)
{
Log.e(TAG, "onProviderEnabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.e(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[] {
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
#Override
public void onCreate()
{
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy()
{
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
}
Copy this code in your Activity when you want to start:
startService(new Intent(this,MyServiceGPS.class));
Create one class globalconstant:
public class globalconstant { public static double lat, lon; }
when you want to current latitude and longitude in your project only write this globalconstant.lat ,globalconstant.lon
Add uses-permission in Manifest
If you want to overlay of your current location then it is better to use default method instead of custom overlay..
Here is default overlay method of current location.
MyLocationOverlay mMyLocationOverlay = new MyLocationOverlay(getApplicationContext(),
Your_MapView);
mMyLocationOverlay.enableMyLocation();
mMyLocationOverlay.onProviderEnabled(LocationManager.NETWORK_PROVIDER);
mapOverlays = map_view.getOverlays();
you can also use GPS
mMyLocationOverlay.onProviderEnabled(LocationManager.GPS_PROVIDER);
you can use this Example for Finding Location Periodically
Is it possible that your android phone is not getting a GPS signal? locationManager.getLastKnownLocation will return null if the GPS has not had time to get a fix yet. Android does not provide a 'give me the location now' method. When the GPS has got a fix, the onLocationChanged() will run. If it is fine with emulator, then there is some problem with the device. Checkout my question Not able to get Location by GPS : Android I had similar problem. What happened with me was that I was receiving location in google maps by network provider. Are you sure you are receiving it through GPS?