LocationManager.requestLocationUpdates not responding - android

I am trying to make an app where an intent service is running in the background and getting the location of the user by the network provider, and when the user is close to his destination(a phone-call gate) its starts another IntentService for the specific gate and get location updates more often by the gps provider.
Problem is when I try to get the location on the more active intentservice it doesn't respond at all.
here is the code in my onStartCommand:
Bundle gateData = intent.getExtras();
gateLat = gateData.getDouble("latitude");
gateLong = gateData.getDouble("longitude");
gateName = gateData.getString("gateName");
gatePhoneNumber = gateData.getString("gatePhoneNumber");
gateId = gateData.getInt("gateId");
Log.i("Active onStartCommand for:", gateId+"\n"+gateName+"\n phone:"+gatePhoneNumber);
helper = new MyGatesOpenHelper(this);
currentGate = helper.getGate(gateId);
currentGate.setMode(Gate.MODE_ONHOLD);
helper.updateGate(currentGate);
results = new float[3];
aManager = (LocationManager)getSystemService(LOCATION_SERVICE);
aListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
makeUseOfNewLocation(location);
Log.i("onLocationChanged coords","Lat:"+location.getLatitude()+" Long:"+location.getLongitude());
}
};
boolean isGpsEnabled = aManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("GPS Status:",isGpsEnabled?"Enabled":"Disabled");
aManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, aListener);
return super.onStartCommand(intent, flags, startId);

Related

find lat and lon in android app

i need to get the lat and lon in a activity. In my oncreate method I tried the code below but im not getting anything when i try to print the Lat. What am I doing wrong. I have included in the manifest file too. I need two strings with the value of Lat and lon
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener lis = new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.d("", "location " + location.getLatitude());
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, lis);

Updating Activity with Latitude/Longitude values returned from a Service

I'm trying to write a simple app that updates the MainActivity with the Lat/Lng values returned by the service. But it always returns the null value. I have added permissions and added TheService.java as service in AndroidManifest.xml file...Kindly tell me where I have gone wrong.
MainActivity.java
public class MainActivity extends Activity {
TextView tv1, tv2;
IntentFilter filter;
receive rec;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1 =(TextView)findViewById(R.id.textView1);
tv2 = (TextView)findViewById(R.id.textView2);
filter = new IntentFilter("Updated");
rec = new receive();
Intent gps_int = new Intent(this,TheService.class);
startService(gps_int);
}
#Override
public void onPause()
{
super.onPause();
unregisterReceiver(rec);
}
#Override
public void onResume()
{
super.onResume();
rec = new receive();
registerReceiver(rec, filter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public class receive extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
tv1.setText(intent.getExtras().getString("lat"));
tv2.setText(intent.getExtras().getString("lon"));
Toast.makeText(getApplicationContext(), "Toast Executed", Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), "BR Latitude "+intent.getExtras().getString("lat"),Toast.LENGTH_SHORT).show();
}
}}
TheService.java
public class TheService extends Service implements LocationListener {
LocationManager lm;
Location loc;
double lat = 0;
double lon = 0;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
lm=(LocationManager)getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
onLocationChanged(loc);
return START_STICKY;
}
#Override
public void onCreate()
{
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
updateui(location);
}
private void updateui(Location location) {
// TODO Auto-generated method stub
lat = location.getLatitude();
lon = location.getLongitude();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent gps_intent = new Intent("Updated");
gps_intent.putExtra("lat", lat);
gps_intent.putExtra("lon", lon);
sendBroadcast(gps_intent);
}
#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
}}
You should use the Google Play Services for the location, that's easier to handle.
What for do you even need a Service? Having a location listener in your Activity is totally fine.
If you want to stay with the Service, than bind the Activity to it, instead of using a Broadcast.

Changing the GPS coordinates with out moving anywhere

**i have used the gps coordinates for calculating the distance using location updates. but problem is that if i am standing at same place the coordinates changes and distance is changing with out moving anywhere. I want to change it only when I have moved min 10 mtrs.
## Activity ##
//Activity
public TextView dist;
public double lati1,lati2,longi1,longi2;
private boolean run1 = false;
private Handler handler1 = new Handler();
private Runnable task1 = new Runnable() {
public void run() {
// TODO Auto-generated method stub
if (run1) {
handler1.postDelayed(this,1000);
if(lati1==0.0&&longi1==0.0)
{
lati1=Service1.lat1;
longi1=Service1.lon1;
}
lati2=Service1.lat1;
longi2=Service1.lon1;
double R=63710;
double dLat=Math.toRadians(lati2-lati1);
double dLon=Math.toRadians(longi2-longi1);
double a=Math.sin(dLat/2)*Math.sin(dLat/2)+
Math.cos(Math.toRadians(lati1))*Math.cos(Math.toRadians(lati2))*
Math.sin(dLon/2)*Math.sin(dLon/2);
double c=2*Math.asin(Math.sqrt(a));
double d=R*c;
d=(double)(Math.round(d*100.00))/1000.00;
distance+=d;
String s=String.format("%.2f", distance);
dist.setText(s);
lati1 = lati2;
longi1 = longi2;
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
dist=(TextView)findViewById(R.id.distancetextView);
Intent i = new Intent(context, Service1.class);
startService(i);
}
## Service ##
//Service
private double new_latitude = 0.0;
private double new_longitude = 0.0;
public static double lat1=0.0,lon1=0.0;
LocationManager locationManager = null;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
locationManager.removeUpdates(this);
super.onDestroy();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
lat1=new_latitude;
lon1=new_longitude;
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}****
I should see the code you are writing. But without it I can say that there is a function, that you call, and it give you location update each X milliseconds. Or you can get the latest updated location, again, I should see your code.
UPDATE:
change this line
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0f, this);
to
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 10.0f, this);
You'll receive updates after moving 10m.
The second parameter is time in millisecond, the third is minimum distance. But it doesn't mean you'll get update exactly at the requested time or requested distance, but rather about it.
//Public or class variable of previous speed initialised on class.
// float previousSpeed;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
new_latitude=location.getLatitude();
new_longitude=location.getLongitude();
float speed = location.getSpeed();
//You could also use location.hasSpeed(), which is a boolean, but it almost
//always returns True
if(speed > DESIRED_LIMIT && previousSpeed > DESIRED_LIMIT){
lat1=new_latitude;
lon1=new_longitude;
}
previousSpeed = speed;
}
So something like that. That condition is not very well optimized or designed. But that is how you get GPS speed from location object. You can tweak the speed limit or the whole condition to get the best results. Or add even more history of speed to monitor.
You can use the location spoofer application from the android market and specify the duration of spoofing the location and also the distance

How to send updated long/lat to server in android?

In my application i want to get the updated location of the mobile user and i want to send it to the server continuously after periodic interval of certain time or after the user travels certain(say 500 meter) distance.I need these things to be done in backgroung.I know for this i have to implement service class. But I am not getting exactly how to do this.I did some work on that.
Can anybody please help me in this issue.
I did following things in the service class.
public class BackGroundService extends Service implements LocationListener{
public static final String Tag = BackGroundService.class.getName();
LocationManager myLocationManager;
Location myLocation;
LocationListener myLocationListener;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void OnCreate()
{
super.onCreate();
Log.d(Tag, "Service Started");
android.os.Debug.waitForDebugger();
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setAccuracy(Criteria.ACCURACY_LOW);
String locationProvider = myLocationManager.getBestProvider(criteria, true);
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000*60*5, 500, myLocationListener);
myLocation = myLocationManager.getLastKnownLocation(locationProvider);
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
longitude = location.getLongitude();
latitude = location.getLatitude();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Provider is disabled");
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d(Tag, "Location Provider is enabled");
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
From here I want know how can i get current lat/long of user and send it to the server.
Answer for my question is.......
public class LocationService extends Service{
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
final LocationManager mlocmag = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final LocationListener mlocList = new MyLocationList();
final Location loc = mlocmag.getLastKnownLocation(LocationManager.GPS_PROVIDER);
UpdateWithNewLocation(loc); // This method is used to get updated location.
mlocmag.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocList);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
}
private void UpdateWithNewLocation(final Location loc) {
// TODO Auto-generated method stub
if(loc!= null)
{
final double lat =loc.getLatitude(); // Updated lat
final double Long = loc.getLongitude(); // Updated long
ConnectMySQL obj = new ConnectMySQL();
obj.call(lat,Long); // Call this method when location is updated and save the data.
}
else
{
String latLongStr = "No lat and longitude found";
Toast.makeText(this, "Your location is "+latLongStr ,Toast.LENGTH_LONG).show();
}
}
public class MyLocationList implements LocationListener
{
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
UpdateWithNewLocation(arg0);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS Disable ", Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"GPS enabled", Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}

GPS tracking in background using service

I have a service for listening the GPS locations and I want to display an updated location in Toast, I run the service in other activity by clicking a Button. The service is created successfully but not showing the toast of updated location. Here is code:
public class locationlistening_service extends Service implements LocationListener {
static LocationManager locationManager;
LocationListener locationListener;
private static final String TAG = "Calculations";
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
run();
}
private void run(){
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setSpeedRequired(true);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
//Acquire a reference to the system Location Manager
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
locationListener = new LocationListener() {
public void onLocationChanged(Location location)
{
recordLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
}
public void recordLocation(Location loc)
{
Toast.makeText(locationlistening_service.this,"Lat: " + String.valueOf(loc.getLatitude()) + " Long: " + String.valueOf(loc.getLongitude()),Toast.LENGTH_SHORT).show();
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
there is call of service in other activity.
public void startButton(View view) {
startService(new Intent(this, locationlistening_service.class));
}
You are never calling requestLocationUpdates(). Hence, nothing is using your LocationManager, LocationListener, or Criteria.
Please be sure to shut down this service when it is no longer needed.

Categories

Resources