android locationlistener - android

I am tring to get the location from a service and its returning null, i dont know what could be the problem. Here my sample code below.
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
locListener = new GpsLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
locListener);
loc = locListener.getLocation();
showMessage("Service started");
if (loc != null) {
latitude = String.valueOf(loc.getLatitude());
longitude = String.valueOf(loc.getLongitude());
}
if (latitude != null && longitude != null) {
connectWebservice();
}
Log.i("trackmeservice", "service started");
}
here my loc is null. Any help will be apprecited thanks;

just check, whether your gps and internet working properly or not.
Add permissions to your manifest file
<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" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
above the Application tag

Related

Android : Can't get location by WIFI on android TV

here's my problem :
I have this code (from this tuto) :
public Location getLocation(Context act) {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (ContextCompat.checkSelfPermission(act, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
It works just fine on AVD and phone but with android TV, it won't work.
My android TV is on "use Wifi to estimate location" ( and is "on" of course) so I thought that even if there is no GPS_PROVIDER it at least should go on NETWORK_PROVIDER but isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); is always false.
I specify that I have wifi on my tv and when I entered google map in my browser it found me.
Can someone please help me understand why it doesn't work or propose an other solution to get my location (apart from google play service, my TV doesn't have it installed)...
EDIT
My manifest :
<!-- lire dans la carte sd -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<!-- écrire dans la carte sd -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!--location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<!-- accès à internet -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- accès à l'état de la connection internet -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- pour enlever le bouton recent app -->
<uses-permission android:name="android.permission.REORDER_TASKS" />
<!-- pour l'AccountManager -->
<uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS"/>
<!-- pareil je crois -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<!-- Pour delete les accounts -->
<uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-feature
android:name="android.hardware.touchscreen"
android:required="false" />
<uses-feature
android:name="android.software.leanback"
android:required="true" />
<uses-feature
android:name="android.hardware.faketouch"
android:required="false" />
<uses-feature
android:name="android.hardware.telephony"
android:required="false" />
<uses-feature
android:name="android.hardware.camera"
android:required="false" />
<uses-feature
android:name="android.hardware.nfc"
android:required="false" />
<uses-feature
android:name="android.hardware.location.gps"
android:required="false" />
<uses-feature android:name="android.hardware.location.network"/>
<uses-feature
android:name="android.hardware.microphone"
android:required="false" />
<uses-feature
android:name="android.hardware.sensor"
android:required="false" />
<supports-screens
android:largeScreens="true"
android:normalScreens="false"
android:requiresSmallestWidthDp="720"
android:smallScreens="false"
android:xlargeScreens="true" />
You can use the LocationServices API in Google Play Services to obtain the user's location. It is a "FusedLocationProvider", incorporating a variety of inputs including Wi-Fi to determine a user's location.
First: Add the COARSE_LOCATION permission:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Then init your object:
FusedLocationProviderClient mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
And get the user's last location through a listener
mFusedLocationClient.getLastLocation()
.addOnSuccessListener(this, new OnSuccessListener<Location>() {
#Override
public void onSuccess(Location location) {
// Got last known location. In some rare situations this can be null.
if (location != null) {
// ...
}
}
});
You may refer with this thread wherein it stated that you will only need these permissions in you manifest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
Then replace the condition to check if you GPS is enabled:
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES,MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener)this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
} //end-if isGPSEnabled
Additional references:
LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is not reliable, why?
There are 2 conditions must be met that LocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) returns true.
Some internal state is ready for network location.
Network location is enabled on setting screen.
.isProviderEnabled(LocationManager.NETWORK_PROVIDER) is always true in Android
...So long as the network provider is not disabled in Settings, isProviderEnabled(LocationManager.NETWORK_PROVIDER)will return true. The provider being enabled has nothing to do with whether the provider will work given your lack of network connection.
Hope this helps!

How to find last location using android

I'm using the following code to get my last know location, but it is not working
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteia();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
Hard to say given the lack of error information. Just a guess ... do you have these in AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

Location manager is shown null

I am trying to track the gps location to be used in my application,
Here is my code,
public class GetGpsCoordinates extends Service implements LocationListener {
boolean isGPSEnabled ;
boolean isNetworkEnabled ;
boolean canGetLocation ;
Location location;
double latitude;
double longitude;
// The minimum distance to change Updates in meters
public static final float MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// meters
// The minimum time between updates in milliseconds
public static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
private final Context Context = GetGpsCoordinates.this;
public final android.content.Context mContext = GetGpsCoordinates.this;
LocationManager locationManager;
public Location getLocation() {
try {
int chkGooglePlayServices = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(Context);
if (chkGooglePlayServices != ConnectionResult.SUCCESS) {
GooglePlayServicesUtil.getErrorDialog(chkGooglePlayServices,
(Activity) mContext, 1122).show();
} else {
locationManager = (LocationManager) getSystemService(mContext.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
I dont know what I am missing, the variable "locationManager" is shown as null.
This is my manifest file,
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.bu"
android:versionCode="2"
android:versionName="2.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="com.bu.permission.MAPS_RECEIVE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:theme="#style/NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomeScreen"
android:label="#string/app_name"
android:theme="#android:style/Theme.Light">
</activity>
<activity
android:name=".PropertySearchTypes.CameraSearch"
android:label="#string/camera_search"
android:screenOrientation="unspecified"/>
<activity
android:name=".PropertySearchTypes.MapSearch"
android:label="#string/map_search" />
<service
android:name=".PropertySearchTypes.PropertyRequestService" >
</service>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="API_KEY" />
</application>
</manifest>
this is my logcat,
06-04 19:21:08.960: D/BatteryService(1499): update start
06-04 19:21:10.101: D/dalvikvm(16760): GC_EXPLICIT freed 17K, 49% free 2778K/5379K, external 688K/1036K, paused 54ms
06-04 19:21:10.210: E/StatusBarPolicy(1552): ecio: 255
06-04 19:21:10.210: E/StatusBarPolicy(1552): iconLevel: 4
06-04 19:21:12.109: D/dalvikvm(18597): JDWP invocation returning with exceptObj=0x40614540 (Ljava/lang/NullPointerException;)
06-04 19:21:12.906: D/dalvikvm(18597): JDWP invocation returning with exceptObj=0x406146a0 (Ljava/lang/NullPointerException;)
06-04 19:21:15.265: D/dalvikvm(15818): GC_EXPLICIT freed 481K, 49% free 3529K/6791K, external 688K/1036K, paused 53ms
06-04 19:21:18.992: D/BatteryService(1499): update start
06-04 19:21:20.265: D/dalvikvm(14873): GC_EXPLICIT freed 199K, 47% free 3590K/6727K, external 688K/1036K, paused 50ms
calling in another activity,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_fragment);
progressDialog = new ProgressDialog(MapSearch.this);
/* getting latitude and longitude*/
GetGpsCoordinates getgpslatlng = new GetGpsCoordinates();
getgpslatlng.getLocation();
Latitude = getgpslatlng.getLatitude();
Longitude = getgpslatlng.getLongitude();
SupportMapFragment sfm = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
map = sfm.getMap();
map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
map.setMyLocationEnabled(true);
}
I have added all th epermissions. I enabled the gps in my device. Even though an exception is raised saying that "locationManager" null and also "chkGooglePlayServices" is null. I ma having Google play services installed in my device.
What's wrong in my code? Please correct me..
Thanks in advance!!
You are initializing a Service from an Activity. This is not the right method to initialize a Service. Service needs to be initialized by Frameworks.
So your Service class does not have a initialized Context. So any calls to methods of Context will fail.
So try this
GetGpsCoordinates getgpslatlng = new GetGpsCoordinates();
getgpslatlng.getLocation(this);
public Location getLocation(Context mContext) {
//use passed Context instead of field mContext
}
This is a wrong way to Initialize LocationManager,
locationManager = (LocationManager) getSystemService(mContext.LOCATION_SERVICE);
Instead of mContext you need to use direct Context class as below,
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
you have not initialized locationmanager, please use
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
before using locationManager

Location is null on device

I am testing my app on a real device and getting a null location when the GPS is on. When I test on the emulator with dummy coordinates it works fine. What is wrong?
locationManager = (LocationManager) context.getSystemService(context.LOCATION_SERVICE);
listener = new MyLocationListener();
viaGps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
viaNetwork = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!viaGps && !viaNetwork) {
tracking = false;
} else {
if (viaGps) {
Log.d("", "gps is on");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else if (viaNetwork) {
Log.d("", "network is on");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, listener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location == null) {
Log.d("", "location not fouond");
}
Try using this , it solved my problem
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Also check your permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
You need a Location listener:
Follow the documentation
Update:
You can also try that easy way: What is the simplest and most robust way to get the user's current location in Android?

android - GPS not accurate

i am trying to show on the map where i am.
I am in Israel and it shows me i am in Egypt.
I tried implementing all of the suggestions of different posts and non helped me solve my problem.
I turned on GPS.
I am connected to the Internet.
When i launch MAPS default android App it shows my real location!
MANIFEST PERMISSIONS:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SEND_SMS" />
<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
I also use the uses-library android:name="com.google.android.maps".
This is the relevant code from the MapActivity which extends LocationListener:
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabled = lm
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabled) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
if(came_from.matches("FollowLocation"))
{
Location location;
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
String providerName = lm.getBestProvider(criteria, true);
// If no suitable provider is found, null is returned.
if (providerName == null)
{
// reflecting changes if distance travel by
// user is greater than 20m from current location
// and every 1 minute
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
location=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else
{
// reflecting changes if distance travel by
// user is greater than 20m from current location
// and every 1 minute
lm.requestLocationUpdates(providerName, 1*60*1000, 20, this);
location=lm.getLastKnownLocation(providerName);
}
gMapView = (MapView) findViewById(R.id.myGMap);
gMapView.setStreetView(true);
mc = gMapView.getController();
if (location != null)
{
lat = location.getLatitude();
lng = location.getLongitude();
mc.setZoom(14);
}
else //in case we didn't get the location yet
{
lat = 32.08;
lng = 35.84;
mc.setZoom(9);
}
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
// Adding zoom controls to Map
gMapView.setBuiltInZoomControls(true);
// Add a location mark
MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
List<Overlay> list = gMapView.getOverlays();
list.add(myLocationOverlay);
}
}
/* This method is called when use position will get changed */
public void onLocationChanged(Location location) {
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// required for interface, not used
}
protected boolean isRouteDisplayed() {
return false;
}
These coordinates: lat = 32.08 lng = 35.84 are some spot in israel...
So..... What am i doing wrong ? Or what am i doing not right ? :P
Thanks!
I'd say that getLastKnownLocation is giving you that erroneous position for some reason. Your default of 32.08, 35.84 won't ever get reached because location will never be null. I'd suggest using the debugger to see which of your calls to getLastKnownLocation is getting hit, and what the value returned is.
I took my code and compared it to a working code from an example in the internet.
Not sure what solved the problem, but i definetly know that you should requestLocationUpdates after you finish to configure everything else.
Other people who encounter this problem - try taking a working code from the internet and comparing it step by step until it works on your app.

Categories

Resources