I have small service implementing LocationListener. I tested it manually with my application and it works properly.
I wrote also a test case for the service.
I used setTestProviderLocation expecting that service will receive location update.
However, it does not happen.
Does anybody know what's a problem? I'd like to emphasize that the same service works in real application.
Test case is added below
package com.gkatz.android.mtg.test;
import java.util.List;
import com.gkatz.android.mtg.LocationService;
import com.gkatz.android.mtg.LocationService.LocationBinder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.test.ServiceTestCase;
public class LocationServiceTest extends ServiceTestCase<LocationService> implements LocationListener{
public LocationServiceTest() {
super(LocationService.class);
// TODO Auto-generated constructor stub
}
#Override
protected void setUp() throws Exception {
// TODO Auto-generated method stub
super.setUp();
}
public void testBinding(){
IBinder locationBinder;
locationBinder = getServiceBinder();
assertNotNull(locationBinder);
}
public void testStart(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
startService(locationIntent);
}
public void testNoStart(){
LocationService locationService = getService();
assertNull(locationService);
}
public void testLocationUpdate() throws InterruptedException{
LocationBinder locationBinder;
LocationService locationService;
Context context = getContext();
LocationManager lm = getLocationManager();
context.registerReceiver(locationReceiver,
new IntentFilter("android.mtg.custom.intent.action.GPS_LOCATION"));
locationBinder = (LocationBinder)getServiceBinder();
assertNotNull(locationBinder);
locationService = getService();
assertNotNull(locationService);
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLongitude(4.890935);
loc.setLatitude(52.373801);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
SystemClock.sleep(3000);
loc.setLongitude(35.2276757);
loc.setLatitude(31.7765488);
loc.setTime(System.currentTimeMillis());
lm.setTestProviderLocation(LocationManager.GPS_PROVIDER, loc);
synchronized (this) {
this.wait(2000);
}
Location lastLoc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
System.out.println("Last known longitude: " + Double.toString(lastLoc.getLongitude()) +
"Last known latitude: " + Double.toString(lastLoc.getLatitude()));
assertEquals(35.2276757, locationService.getLongitude());
assertEquals(31.7765488, locationService.getLatitude());
context.unregisterReceiver(locationReceiver);
lm.removeTestProvider(LocationManager.GPS_PROVIDER);
}
private BroadcastReceiver locationReceiver=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
assertTrue(intent.getAction().equals("android.mtg.custom.intent.action.GPS_LOCATION"));
System.out.println("Action received: " + intent.getAction());
this.notify();
}
};
private IBinder getServiceBinder(){
Intent locationIntent = new Intent(getContext(), LocationService.class);
return bindService(locationIntent);
}
private LocationManager getLocationManager(){
LocationManager lm = (LocationManager)
getContext().getSystemService(Context.LOCATION_SERVICE);
lm.addTestProvider(LocationManager.GPS_PROVIDER,
true, true, true, true, true, true, true,
Criteria.POWER_LOW, Criteria.ACCURACY_FINE);
lm.setTestProviderStatus(LocationManager.GPS_PROVIDER,
LocationProvider.AVAILABLE, null, System.currentTimeMillis());
lm.setTestProviderEnabled(LocationManager.GPS_PROVIDER, true);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,this);
return lm;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
System.out.println("LocationServiceTest, onLocationChanged, lon:" +
Double.toString(location.getLongitude()) + ", lat:" +
Double.toString(location.getLatitude()));
}
#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
}
}
Try with
// Register the listener with the Location Manager to receive location updates
lm.requestLocationUpdates("YOUR PROVIDER", 0, 0, YOUR_LOCATION_LISTENER);
Found at Location guide of Android Developers
Related
I am developing an android application that makes use of new android geofencing API and I want to register more than 100 Geofences.
I'm having an update to my location in the background every 1 minute, and onHandleIntent method in the IntentService class I'm calculating the distance between current location and getting the closest 100 and then I need to monitor these 100 geofences.
The problem is that I am not able to add the closest 100 geofences after getting the current location, and all this have to work when the application is closed.
Here's my code:
package com.example.android.geofence;
import java.util.ArrayList;
import java.util.List;
import android.app.Dialog;
import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.NotificationCompat.Builder;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.Toast;
import com.example.android.geofence.GeofenceUtils.REMOVE_TYPE;
import com.example.android.geofence.GeofenceUtils.REQUEST_TYPE;
import com.example.android.geofence.MainActivity.GeofenceSampleReceiver;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.Geofence;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationClient.OnAddGeofencesResultListener;
public class LocationService extends IntentService implements OnAddGeofencesResultListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {
private String TAG = this.getClass().getSimpleName();
public static int notificationID = 0;
LocationClient geoLocationClient;
public String monitoredLounges = "";
public LocationService() {
super("Fused Location");
}
public LocationService(String name) {
super("Fused Location");
}
#Override
public void onCreate() {
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (resultCode == ConnectionResult.SUCCESS) {
geoLocationClient = new LocationClient(this, this, this);
// when I'm using connect() in order to addgeofences my application stops unexpectedly
geoLocationClient.connect();
}
}
#Override
protected void onHandleIntent(Intent intent) {
Location location = intent.getParcelableExtra(LocationClient.KEY_LOCATION_CHANGED);
if(location != null){
RegisterGeofences(location);
Log.i(TAG, "onHandleIntent " + location.getLatitude() + "," + location.getLongitude());
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Builder noti = new NotificationCompat.Builder(this);
noti.setContentTitle("Fused Location");
noti.setContentText(notificationID + "," + location.getLatitude() + "," + location.getLongitude());
noti.setSmallIcon(R.drawable.ic_launcher);
notificationManager.notify(notificationID, noti.build());
notificationID++;
}
}
public void RegisterGeofences(Location _location) {
MySQLiteHelper myDbHelper = new MySQLiteHelper(this);
List<Lounge> closestRegions = myDbHelper.getClosestRegions(_location.getLatitude(), _location.getLongitude());
ArrayList<Geofence> geofenceList = new ArrayList<Geofence>();
int regionIndex = 0;
for (Region cn : closestRegions){
regionIndex++;
if(regionIndex> 100) break;
Geofence geofence = new Geofence.Builder()
.setRequestId(cn.getTitle())
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT)
.setCircularRegion(cn.getLatitude(), cn.getLongitude(), (float) 500.00)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
.build();
monitoredLounges += cn.getTitle() + "&";
geofenceList.add(geofence);
}
PendingIntent geoFencePendingIntent = PendingIntent.getService(this, 0,
new Intent(this, GeofenceIntentService.class), PendingIntent.FLAG_UPDATE_CURRENT);
geoLocationClient.addGeofences(geofenceList, geoFencePendingIntent, this);
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onAddGeofencesResult(int arg0, String[] arg1) {
// TODO Auto-generated method stub
}
}
Note also that before adding RegisterGeofences Method everything concerning updatelocations was working perfectly in the background
IntentService doesn't run after a the job is done.(i.e) It destroys the service after some time. Rather, You create a service and run them. Because GeoFences run only when the geoLocationClient is connected and available. Also disconnect the geoLocationClient in the service onDestroy()
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
double latitude;
double longitude;
private LocationManager lm;
ArrayList<Point> pt;
Point p;
private Context context;
private Location loc;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(){
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
loc = location;
Toast.makeText(getApplicationContext(), "Lat: " + loc.getLatitude() + "Long: " + loc.getLongitude(), Toast.LENGTH_LONG).show();
updateList();
}
#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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
this.loc = null;
pt = new ArrayList<Point>();
p = new Point();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
So, in this code, my intention is to save a list of Points in an ArrayList of Points that will be use later. But all the points (latitude and longitude) have the same value, once i have the first value, all the others values are the same, its seems like onLocationChanged is never called.
Can someone help me?
You have a global point p that you're overwriting every call to updateList. Since you aren't creating a new point ever, this overwrites the old values. That means every element in your list will always have the most recent values, rather than the value at that time.
Also, why are you using class variables everywhere rather than passing parameters to functions? I have a feeling you don't understand Java or references very well.
Edit:
Here's what your code should look like, with locals used correctly:
package com.example.pointkeeper;
import java.util.ArrayList;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util
public class ServicePointKeeper extends Service implements LocationListener{
private LocationManager lm;
ArrayList<Point> pt;
private final static long TEMPO_DE_ATUALIZACAO = 1 * 60 * 1000 ;
private final static float DISTANCIA_DE_ATUALIZACAO = 1 ;
public void setGPS(){
Criteria criteria = new Criteria();
criteria.setAccuracy( Criteria.ACCURACY_FINE );
criteria.setAltitudeRequired(true);
String provider = lm.getBestProvider(criteria, true);
if ( provider == null ) {
Log.d("SistemaGPS.ativar", "Nenhum provedor encontrado.");
} else {
Log.d("SistemaGPS.ativar", "Provedor utilizado: " + provider);
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
lm.requestLocationUpdates(provider, TEMPO_DE_ATUALIZACAO, DISTANCIA_DE_ATUALIZACAO , this);
}
}
public void updateList(Location loc){
Point p = new Point();
p.setLatitude(loc.getLatitude());
p.setLongitude(loc.getLongitude());
pt.add(p);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Lat: " + location.getLatitude() + "Long: " + location.getLongitude(), Toast.LENGTH_LONG).show();
updateList(location);
}
#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 int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "Serviço iniciado", Toast.LENGTH_SHORT).show();
pt = new ArrayList<Point>();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
setGPS();
Toast.makeText(getBaseContext(), "GPS setado", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Serviço parado", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "Lat: " + latitude + "Long: " + longitude, Toast.LENGTH_SHORT).show();
Intent it = new Intent(getApplicationContext(), ShowPoints.class);
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Bundle b = new Bundle();
b.putParcelableArrayList("points", pt);
it.putExtras(b);
startActivity(it);
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
i'm trying to automatically update my location and have some other part of cloud related code working when location is changed. here is the code of my service:
package com.salesforce.samples.templateapp;
import java.util.HashMap;
import org.json.JSONArray;
import com.salesforce.androidsdk.app.ForceApp;
import com.salesforce.androidsdk.rest.RestClient;
import com.salesforce.androidsdk.rest.RestRequest;
import com.salesforce.androidsdk.rest.RestResponse;
import com.salesforce.androidsdk.rest.RestClient.AsyncRequestCallback;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class MyServices extends Service {
RestClient client;
double plat;
double plong;
int Two_Min=2*60*1000;
// TextView infoText;
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Location Updation has started", Toast.LENGTH_LONG)
.show();
Log.v("X","Response:in onStartCommand()");
//Intent in = new Intent().setClass(MyServices.this, GPSUpdate.class);
//in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(in);
detectLocation();
return START_STICKY;
}
private void detectLocation() {
// TODO Auto-generated method stub
Toast.makeText(this, "Inside detectlocation()", Toast.LENGTH_SHORT)
.show();
LocationManager lm1 = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll1 = new MyLocationListetner();
Criteria crit = new Criteria();
crit.setAccuracy(Criteria.ACCURACY_FINE);
String best = lm1.getBestProvider(crit, false);
// lm1.requestLocationUpdates(best, 0, 1, ll1);
Log.v("X",
"Response:After creating lm and ll ");
// boolean b1=lm1.addGpsStatusListener((Listener) ll1);
//Log.v("X",
// "Response: "+b1);
lm1.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll1);
Log.v("X",
"Response:After lm1.requestLocationUpdates ");
/*Location loc = null;
loc.getLatitude();
loc.getLongitude();
Log.v("X","Response:"+loc);
ll1.onLocationChanged(loc);*/
}
class MyLocationListetner implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("X","Response:inside onLocationChanged ");
Toast.makeText(getApplicationContext(), "inside onLocationChanged()", Toast.LENGTH_LONG).show();
//Log.v("X","Response:"+location);
if (location != null) {
plat = location.getLatitude();
plong = location.getLongitude();
Log.d("X",
"Response:Location " + Double.toString(plat)+Double.toString(plong));
String objectType = "akshayg__User__c";
String objectId = "a02900000089fK3";
HashMap<String, Object> fields = new HashMap<String, Object>();
fields.put("Name", "Ashish");
// fields.put("akshayg__Donor_Location__Latitude__s",
// Double.toString(plat));
// fields.put("akshayg__Donor_Location__Longitude__s",
// Double.toString(plong));
RestRequest request = null;
try {
request = RestRequest.getRequestForUpdate(
getString(R.string.api_version), objectType,
objectId, fields);
// Toast.makeText(this, "Location Updation has started",
// Toast.LENGTH_LONG).show();
} catch (Exception e) {
// printHeader("Could not build update request");
printException(e);
return;
}
client.sendAsync(request, new AsyncRequestCallback() {
#Override
public void onSuccess(RestRequest request,
RestResponse result) {
// Toast.makeText(this,
// ""+Double.toString(plat)+","+Double.toString(plong),
// Toast.LENGTH_LONG).show();
try {
//Toast.makeText(this, "Location Updated",Toast.LENGTH_LONG).show();
Log.v("X",
"Response:inside onSuccess() " + result.toString());
/*JSONArray records = result.asJSONObject()
.getJSONArray("records");
for (int i = 0; i < records.length(); i++) {
// listAdapter.add(records.getJSONObject(i).getString("Name"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Phone_Number__c"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Latitude__s"));
// listAdapter.add(records.getJSONObject(i).getString("akshayg__Donor_Location__Longitude__s"));
}
*/
}
catch (Exception e) {
onError(e);
}
}
#Override
public void onError(Exception exception) {
Log.v("X",
"Response: " + exception.toString());
// Toast.makeText(MainActivity.this,
// MainActivity.this.getString(ForceApp.APP.getSalesforceR().stringGenericError(),
// exception.toString()),
// Toast.LENGTH_LONG).show();
}
});
}
}
private void printException(Exception e) {
String err = "Error: " + e.getClass().getSimpleName();
Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG)
.show();
}
#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
}
}
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Location Updation has stoped", Toast.LENGTH_LONG)
.show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
the toasts till "inside detectLocation" are popped up and log entries made till
04-04 00:42:34.687: V/X(10217): Response:After lm1.requestLocationUpdates
but beyond that the code is just unreachable...
even the GPS sign is shown in action bar but the toast for displaying location is not popped... pls help....!!!
In requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, Two_Min, ll1) you're passing Two_Min (which you've set to 5*60*1000 = 300000) into the minDistance paramter which should be a number of metres. Try setting minDistance to 0 instead.
So I am trying to get current latitude and longitude and comparing it with the data I stored in my database using cursor...but when I am trying to run this app on my cell then its getting force close after some time..don't know why what the reason is....
Here's the code for getting current location and comparing it with database
package com.example.alert;
import java.util.ArrayList;
import java.util.List;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;
public class service extends Service{
LocationManager lm;
DatabaseHelper db=new DatabaseHelper(this);
List<String> arlist=new ArrayList<String>();
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onCreate() {
LocationManager lm=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener ll=new MyLocationListener();
//lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 5*60*10000, 0, ll);
lm.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, ll);
Toast.makeText(this, "Background Service Created", Toast.LENGTH_LONG).show();
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
}
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
// Intent myIntent=new Intent(service.this,CurrentLocation.class);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
if(loc!=null)
{
double x;
SQLiteDatabase y = db.getWritableDatabase();
String Text = "My current location is: " +"Latitud = " + loc.getLatitude() +"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
// String t=loc.getLatitude().toString();
Cursor cr=null;
cr=y.rawQuery("SELECT LATITUDE FROM"+ "data",null);
cr.moveToFirst();
while(cr.moveToNext()) {
arlist.add(cr.getString(cr.getColumnIndex("Latitude")));
}
for(int i=0;i<arlist.size();i++){
if(arlist.get(i)==Double.toString(loc.getLatitude())){
Intent myIntent=new Intent(service.this,SilVib.class);
startActivity(myIntent);
}
}
/* cr.moveToFirst();
while(!cr.isAfterLast()) {
al.add(cr.getString(cr.getColumnIndex(dbAdapter.KEY_NAME))); //add the item
cr.moveToNext();
}*/
// lm.addProximityAlert(loc.getLatitude(), loc.getLongitude(), 10009,, intent)
//for loop, alerters retrieving one by one
// x= calcDistance(loc.getLatitude(),loc.getLongitude(),z,y);
// if(x<1){
// Intent myIntent = new Intent(ViewAlerters.this,CallMode.class);
// startActivity(myIntent);
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Disabled - #From :Alert Me",Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText( getApplicationContext(),"Gps Enabled - #From :Alert Me",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
/* public double calcDistance(double latA, double longA, double latB, double longB) {
double theDistance = (Math.sin(Math.toRadians(latA)) * Math.sin(Math.toRadians(latB)) + Math.cos(Math.toRadians(latA)) * Math.cos(Math.toRadians(latB)) * Math.cos(Math.toRadians(longA - longB)));
return new Double((Math.toDegrees(Math.acos(theDistance))) * 69.09*1.6093);
}
*/
}
I am writing a code that brings current location but it is not giving me the location because it never calls onLocationChanged() .Is there any way to find the location.
mobileLocation is coming 0 for this case, so the execution goes to the else block.
My code is
public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;
public FindLocation(Context ctx){
locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
locListener = 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(Location location) {
System.out.println("mobile location is in listener="+location);
mobileLocation = location;
}
};
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
if (mobileLocation != null) {
locManager.removeUpdates(locListener);
String londitude = "Londitude: " + mobileLocation.getLongitude();
String latitude = "Latitude: " + mobileLocation.getLatitude();
String altitiude = "Altitiude: " + mobileLocation.getAltitude();
String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
String time = "Time: " + mobileLocation.getTime();
Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
} else {
System.out.println("in find location 4");
Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
}
}
}
i run my app on real device .
i use network instead of GPS and onLocationChanged is called:
locMan.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null);
Do you never get a location or only as you write in your comment "sometimes it gets location but not at the time of click."?
Might be that your code is faster than LocationManager, which might not yet have called onLocationChanged(). Change your code in order to get the last known location, or wait until your locListener was called:
locManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 1000, 1, locListener);
mobileLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {
LocationManager.NETWORK_PROVIDER need network, but it is real, not precise; if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!
I thing you forgot permission
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<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" />
OR
Declare Proper Class like
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location arg0) {
latitude = arg0.getLatitude();
longitude = arg0.getLongitude();
}
}
Directly after locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener), add the following code:
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locListener);
EDIT: corrected the code thanks to the comment by #Fabian Streitel.
import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;
import org.json.JSONObject;
import java.util.List;
public class AndroidLocationServices extends Service {
PowerManager.WakeLock wakeLock;
String MODULE="AndroidLocationServices",TAG="";
private LocationManager locationManager;
double getLattitude=0,getLogitude=0;
private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
preferences=getSharedPreferences(GlobalConfig.PREF_NAME, MODE_PRIVATE);
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500, 0, listener);
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);
}
public LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
location.setAccuracy(100);
if (location == null)
return;
getLattitude=location.getLatitude();
getLogitude=location.getLongitude();
Log.e("latitude", getLattitude + "");
Log.e("longitude", getLogitude + "");
}
#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 onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// wakeLock.release();
}
}
Manifest:
<service android:name=".services.AndroidLocationServices"/>
Start Service before use:
startService(new Intent(this, AndroidLocationServices.class));
In my case the app was not asking for permissions. Although I have added the permissions in menifest file. So I was not able to allow my app to access the location.
As a fix, I manually went to: Settings->Permissions->Your location and enabled the location permission for my under-development app. And that fixed my problem.
I assume that this issue is only when the app is installed through Android Studio. I hope it will not occur when the app is installed from Google Play.