Background process works but doesn't update data? - android

I am trying to make a background service which runs even when app is closed, it would get current location and once person is close to destination the app would start up.
package als.wakeup;
import com.google.android.gms.maps.model.LatLng;
import android.app.Service;
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.Log;
import android.widget.Toast;
public class Awake_Alarm extends Service implements LocationListener{
Location location;
ConversePrefs cp;
ConversePrefs_sets cpss;
LatLng final_dest;
Settings sets;
double final_range;
LocationManager locationManager;
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
final String provider = locationManager.getBestProvider(criteria, true);
location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
cp = new ConversePrefs(this);
cpss = new ConversePrefs_sets(this);
sets = new Settings(this);
final_range = cp.GetIntSetting("Range", 250);
final_dest = cp.GetCoords();
if(cpss.GetIntSetting(sets.def_units_name, 0) == 1){
final_range = final_range * 1.09361;
}
Toast.makeText(getApplicationContext(), "Started", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING");
super.onCreate();
}
public double distanceGet(LatLng StartP, LatLng EndP) {
double lat1 = StartP.latitude;
double lat2 = EndP.latitude;
double lon1 = StartP.longitude;
double lon2 = EndP.longitude;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return 6366000 * c;
}
#Override
public void onLocationChanged(Location arg0) {
LatLng me = new LatLng(location.getLatitude(), location.getLongitude());
double dest = distanceGet(me, final_dest);
if(dest <= final_range){
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING-"+String.valueOf(dest));
}
Toast.makeText(getApplicationContext(), String.valueOf(dest)+" Away2-.", Toast.LENGTH_LONG).show();
Log.d("STATUS", "RUNNING2-"+String.valueOf(dest));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
It seems to work fine, it launches etc and runs, and when location is changed it makes Toast text as required, but: The distance to target doesn't get updated, say I launch app, click start service and distance to destination is 1500 Meters, when location gets changed it still makes toast text saying: "1500 meters"
What am I doing wrong?

Related

get location requestLocationUpdates service?

I try to make a locationing service but somehow i cant make it work. Lat and Lng are always NULL.
I had some exceptions on locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
My CODE :
package com.example.outmane.training;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service
{
private LocationManager locManager;
private LocationListener locListener = new myLocationListener();
static final Double EARTH_RADIUS = 6371.00;
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Handler handler = new Handler();
Thread t;
#Override
public IBinder onBind(Intent intent) {return null;}
#Override
public void onCreate() {}
#Override
public void onDestroy() {}
#Override
public void onStart(Intent intent, int startid) {}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
final Runnable r = new Runnable()
{ public void run()
{
Log.v("Debug", "Hello");
location();
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(r, 5000);
return START_STICKY;
}
public void location(){
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try{
gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex){}
try{
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch(Exception ex){}
Log.v("Debug", "in on create.. 2");
if (gps_enabled) {
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
Log.v("Debug", "Enabled..");
}
if (network_enabled) {
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
Log.v("Debug", "Disabled..");
}
Log.v("Debug", "in on create..3");
}
private class myLocationListener implements LocationListener
{
double lat_old=0.0;
double lon_old=0.0;
double lat_new;
double lon_new;
double time=10;
double speed=0.0;
#Override
public void onLocationChanged(Location location) {
Log.v("Debug", "in onLocation changed..");
if(location!=null){
locManager.removeUpdates(locListener);
//String Speed = "Device Speed: " +location.getSpeed();
lat_new=location.getLongitude();
lon_new =location.getLatitude();
String longitude = "Longitude: " +location.getLongitude();
String latitude = "Latitude: " +location.getLatitude();
double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);
speed = distance/time;
Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
+distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
lat_old=lat_new;
lon_old=lon_new;
}
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
double Radius = EARTH_RADIUS;
double dLat = Math.toRadians(lat2-lat1);
double dLon = Math.toRadians(lon2-lon1);
double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
Math.sin(dLon/2) * Math.sin(dLon/2);
double c = 2 * Math.asin(Math.sqrt(a));
return Radius * c;
}
}
Try using Fused Loaction Provider. It will take care of all the heavy stuff. And you will get callbacks for when location is available.
http://developer.android.com/training/location/retrieve-current.html

I m calculating distance between 2 points in map in real time as the user walks if destination is fixed

I m trying to calculate distance in real time between 2 co-ordinates as the user walks. I am using a while loop which hangs my application. I have no idea how to rectify it. Can anyone suggest a alternative to it.
package com.ankur.mapdemo;
import android.app.Activity;import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
public class AlertReminder extends Activity implements OnCheckedChangeListener,LocationListener {
CheckBox cb1,cb2,cb3,cb4,cb5,cb6,cb7;
TextView tv1,tv2;
double currentlatitude=0,currentlongitude=0;
float dis = 0;
Location mostrecent = new Location("");
LocationManager locationManager;
LocationListener locationListener;
Context context;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertreminder);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
/*
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
*/
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 1, this);
tv2= (TextView)findViewById(R.id.location1);
tv1 = (TextView)findViewById(R.id.currentlocation);
cb1 = (CheckBox)findViewById(R.id.sjt);
cb1.setOnCheckedChangeListener(this);
cb2 = (CheckBox)findViewById(R.id.tt);
cb2.setOnCheckedChangeListener(this);
cb3 = (CheckBox)findViewById(R.id.smv);
cb3.setOnCheckedChangeListener(this);
cb4 = (CheckBox)findViewById(R.id.mb);
cb4.setOnCheckedChangeListener(this);
cb5 = (CheckBox)findViewById(R.id.gdn);
cb5.setOnCheckedChangeListener(this);
cb6 = (CheckBox)findViewById(R.id.cdmm);
cb6.setOnCheckedChangeListener(this);
cb7 = (CheckBox)findViewById(R.id.allmart);
cb7.setOnCheckedChangeListener(this);
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
currentlatitude = location.getLatitude();
currentlongitude = location.getLongitude();
makeuseofnewlocation(location);
//newlocation(location);
tv1.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude() + ", Distance:" + dis);
}
private void makeuseofnewlocation(Location location1) {
// TODO Auto-generated method stub
mostrecent = location1;
//currentlatitude = location.getLatitude();
//currentlongitude = location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
Log.d("Latitude","status");
}
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
int i = arg0.getId();
if(i == R.id.allmart)
{
if(arg1)
{
double destLat = 12.972887;
double destLong = 79.159715;
Location me = new Location("");
Location dest = new Location("");
me.setLatitude(currentlatitude);
me.setLongitude(currentlongitude);
dest.setLatitude(destLat);
dest.setLongitude(destLong);
float dist = me.distanceTo(dest);
while(dist > 50)
{
makeuseofnewlocation(mostrecent);
//cbskjcbkcb
//cbshbcbcbhchj
//currentlatitude = l1.getLatitude();
//currentlongitude = l1.getLongitude();
me.setLatitude(mostrecent.getLatitude());
me.setLongitude(mostrecent.getLongitude());
dest.setLatitude(destLat);
dest.setLongitude(destLong);
dist = me.distanceTo(dest);
dis = dist;
}
if(dist <= 50)
{
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.notify)
.setContentTitle("ALERT")
.setContentText("this is a notification")
.setSound(soundUri);
notificationManager.notify(0, mBuilder.build());
}
}
}
}
}
`
As long as the distance is greater than 50, it will stay inside the loop, but won't update anything in your layout. I would create a new thread for this calculation (google multithreading), and let your main thread only get those values and update them in your layout.

Not getting Latitude and longitude after every 1 minute in android

I want to make an android program in that I get latitude and longitude in Toast after each 1 minute interval and populated on toast even after my application closed.
I have tried as below,But I only getting on time latitude and longitude,Please tell me what should i do for it to get continuously lat long in toast.My code is as below:
GPStracker.java
package com.epe.trucktrackers;
import java.util.Timer;
import java.util.TimerTask;
import utils.Const;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
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.Toast;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
private Timer timer;
private long UPDATE_INTERVAL;
public static final String Stub = null;
LocationManager mlocmag;
LocationListener mlocList;
private double lat, longn;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
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 (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;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
System.out.println(":::::::::::Ne lat longs............!!!" + message);
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(mContext, latitude + " " + longitude, Toast.LENGTH_LONG)
.show();
/* UpdateWithNewLocation(location); */
System.out.println(":Location chane");
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Activity.java
package com.epe.trucktrackers;
import org.json.JSONException;
import org.json.JSONObject;
import utils.Const;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import backend.BackendAPIService;
public class MainActivity extends Activity {
EditText et_registration_no;
Button btn_register;
static GPSTracker gps;;
String lat, lng;
private ProgressDialog pDialog;
String udid;
String status;
String tracking_id;
String UDID;
String lati;
String longi;
String registration_no;
int flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_registration_no = (EditText) findViewById(R.id.et_truck_no);
btn_register = (Button) findViewById(R.id.btn_reg);
TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
udid = TelephonyMgr.getDeviceId();
gps = new GPSTracker(MainActivity.this);
btn_register.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(
getApplicationContext(),
"Your Location is - \nLat: " + latitude
+ "\nLong: " + longitude, Toast.LENGTH_LONG)
.show();
lat = latitude + "";
lng = longitude + "";
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
new RegistartionApi().execute();
System.out
.println("::::::::::::::service started:::::::::::::");
}
});
// api call for the REGISTARTION ..!!
}
class RegistartionApi extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
System.out
.println("==========inside preexecute===================");
}
#Override
protected Void doInBackground(Void... arg0) {
String registrationURL = Const.API_REGISTRATION + "?UDID=" + udid
+ "&latitude=" + lat + "&longitude=" + lng
+ "&registration_no="
+ et_registration_no.getText().toString().trim();
registrationURL = registrationURL.replace(" ", "%");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::Registration url:::::::::::;"
+ registrationURL);
String jsonStr = sh.makeServiceCall(registrationURL,
BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
System.out.println("=============MY RESPONSE==========" + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject c = new JSONObject(jsonStr);
if (jsonObj.has("status")) {
status = jsonObj.getString("status");
{
if (status.equalsIgnoreCase("success")) {
flag = 1;
c = jsonObj.getJSONObject("truck_tracking");
tracking_id = c.getString("tracking_id");
UDID = c.getString("UDID");
lati = c.getString("latitude");
longi = c.getString("longitude");
registration_no = c
.getString("registration_no");
} else {
flag = 2;
Toast.makeText(MainActivity.this, "Failed",
Toast.LENGTH_SHORT).show();
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 1) {
Toast.makeText(MainActivity.this, "Registration Done",
Toast.LENGTH_SHORT).show();
/*Intent i = new Intent(getApplicationContext(), GPSTracker.class);
startService(i);*/
}
}
}
}
Try this one.
package com.sample.location;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled = false;
boolean network_enabled = false;
public boolean getLocation(Context context, LocationResult result) {
// I use LocationResult callback class to pass location value from
// MyLocation to user code.
locationResult = result;
if (lm == null)
lm = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
// exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
locationListenerGps);
if (network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
timer1 = new Timer();
timer1.schedule(new GetLastLocation(), 60*1000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
/**
* Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderDisabled(String provider) {
}
/**
* Called when the provider is enabled by the user.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderEnabled(String provider) {
}
/**
* Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
* #param provider
* the name of the location provider associated with this update.
* #param status
* OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available.
* #param extras
* an optional Bundle which will contain provider specific status variables.
A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.
satellites - the number of satellites used to derive the fix
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
/**
* Called when the location has changed.
* There are no restrictions on the use of the supplied Location object.
* #param location
* The new location, as a Location object.
*/
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
/**
* Called when the provider is disabled by the user. If requestLocationUpdates is called on an already disabled provider, this method is called immediately.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderDisabled(String provider) {
}
/**
* Called when the provider is enabled by the user.
* #param provider
* the name of the location provider associated with this update.
*/
#Override
public void onProviderEnabled(String provider) {
}
/**
* Called when the provider status changes. This method is called when a provider is unable to fetch a location or if the provider has recently become available after a period of unavailability.
* #param provider
* the name of the location provider associated with this update.
* #param status
* OUT_OF_SERVICE if the provider is out of service, and this is not expected to change in the near future; TEMPORARILY_UNAVAILABLE if the provider is temporarily unavailable but is expected to be available shortly; and AVAILABLE if the provider is currently available.
* #param extras
* an optional Bundle which will contain provider specific status variables.
A number of common key/value pairs for the extras Bundle are listed below. Providers that use any of the keys on this list must provide the corresponding value as described below.
satellites - the number of satellites used to derive the fix
*/
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
/**
* The GPS location and Network location to be calculated
* in every 5 seconds with the help of this class
*
*/
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
/**
* This abstract class is used to get the location from other class.
*
*/
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
}
In your Activity.java
LocationManager myLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
MyLocation myLocation = new MyLocation();
myLocation.getLocation(getApplicationContext(), locationResult);
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
}
};

Why I'm getting 0 latitude and longitude?

I have 3 fragment class in tab layout and in one of them I have implemented a button to get the current location(latitude & longitude). Everything works fine except the latitude and longitude showing value 0.
package com.swipetab.example;
import java.util.Calendar;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class FragmentC extends Fragment {
Button Date, Time, GpsBtn;
GPSTracker gps;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_c, container,
false);
Date = (Button) myFragmentView.findViewById(R.id.button1);
Time = (Button) myFragmentView.findViewById(R.id.button2);
GpsBtn = (Button) myFragmentView.findViewById(R.id.button3);
Date.setOnClickListener(DateOnClickListener);
Time.setOnClickListener(TimeOnClickListener);
GpsBtn.setOnClickListener(GPSOnClickListener);
return myFragmentView;
}
OnClickListener DateOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
showDatePicker();
}
};
OnClickListener TimeOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
showTimePicker();
}
};
OnClickListener GPSOnClickListener = new OnClickListener() {
#Override
public void onClick(View arg0) {
showGPSLocation();
}
};
private void showDatePicker() {
DatePicker date = new DatePicker();
/**
* Set Up Current Date Into dialog
*/
Calendar calender = Calendar.getInstance();
Bundle args = new Bundle();
args.putInt("year", calender.get(Calendar.YEAR));
args.putInt("month", calender.get(Calendar.MONTH));
args.putInt("day", calender.get(Calendar.DAY_OF_MONTH));
date.setArguments(args);
/**
* Set Call back to capture selected date
*/
date.setCallBack(ondate);
date.show(getFragmentManager(), "Date Picker");
}
private void showTimePicker() {
Time time = new Time();
/**
* Set Up Current Time Into dialog
*/
Calendar calender = Calendar.getInstance();
Bundle args = new Bundle();
args.putInt("hour", calender.get(Calendar.HOUR_OF_DAY));
args.putInt("min", calender.get(Calendar.MINUTE));
time.setArguments(args);
/**
* Set Call back to capture selected date
*/
time.setCallBack(ontime);
time.show(getFragmentManager(), "Time Picker");
}
private void showGPSLocation() {
gps = new GPSTracker(getActivity());
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(
getActivity(),
"Your Location is - \nLat: " + latitude + "\nLong: "
+ longitude, Toast.LENGTH_LONG).show();
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
OnDateSetListener ondate = new OnDateSetListener() {
#Override
public void onDateSet(android.widget.DatePicker arg0, int year,
int month, int day) {
// TODO Auto-generated method stub
String TabOfFragmentB = ((MainActivity) getActivity())
.getTabFragmentB();
FragmentB fragmentB = (FragmentB) getActivity()
.getSupportFragmentManager().findFragmentByTag(
TabOfFragmentB);
String y = Integer.toString(year);
String m = Integer.toString(month);
String d = Integer.toString(day);
String dat = y.concat("-") + m.concat("-") + d;
fragmentB.b_updateDate(dat);
Toast.makeText(
getActivity(),
String.valueOf(year) + "-" + String.valueOf(month) + "-"
+ String.valueOf(day), Toast.LENGTH_LONG).show();
}
};
OnTimeSetListener ontime = new OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker arg0, int hourOfDay, int min) {
// TODO Auto-generated method stub
String TabOfFragmentB = ((MainActivity) getActivity())
.getTabFragmentB();
FragmentB fragmentB = (FragmentB) getActivity()
.getSupportFragmentManager().findFragmentByTag(
TabOfFragmentB);
int hour;
String am_pm;
if (hourOfDay > 12) {
hour = hourOfDay - 12;
am_pm = "PM";
} else {
hour = hourOfDay;
am_pm = "AM";
}
String h = Integer.toString(hour);
String m = Integer.toString(min);
String t = h.concat(":") + m + " " + am_pm;
fragmentB.b_updateTime(t);
Toast.makeText(getActivity(),
String.valueOf(hour) + "-" + String.valueOf(min),
Toast.LENGTH_LONG).show();
}
};
}
GPSTracker class
package com.swipetab.example;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
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;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
private Location getLocation() {
// TODO Auto-generated method stub
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
System.out.println("Please Enable!!");
} else {
this.canGetLocation = true;
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;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS settings");
// Setting Dialog Message
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
your if conditions, are the problems i think.if GPS is not enable then you fetch the location from network provider and for network provider your option ->(use wireless network )should be enable in location service settings and your internet connection should be working.and for basic working please find the link.enter link description here
Have you added this to your AndroidManifest.xml file?
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
You can change the coordinates using the monitor control in android studio. You must go to Tools->Android->Android Device Monitor. It show a windows, in this windows, you choose Emulator Control, in the bottom you can change the coordinates (longitude, altitude)

Android: Map Controler's animateTo method doesn't work properly

I'm trying to animate a new location on the map when the location changed (or when I supply a mock location via the telnet)
this is what I use
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
Though the Toast shows the lontitute and latitute properly, app doesn't animate to given cordinates. What could be the problem?? Please find my whole code below.
package com.mayuonline.androidgps;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
public class GPSActivity extends MapActivity {
MapController mapController;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setting up map
MapView mapview = (MapView)findViewById(R.id.mapview);
mapview.setBuiltInZoomControls(true);
mapController = mapview.getController();
// mapController.setZoom(16);
LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
LocationListener locationListener = 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) {
makeUseOfNewLocation(location);
//Toast.makeText(getApplicationContext(), "New Locationdd", Toast.LENGTH_LONG).show();
}
private void makeUseOfNewLocation(Location location) {
double lon = (double)location.getLongitude();
double lat = (double)location.getLatitude();
int lontitue = (int)lon;
int latitute = (int)lat;
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
I figured out the issue. It is something to do with getLongitude method :)
I need to multiply by 1E6 as given below.
double lon = (double) (location.getLongitude() * 1E6);
double lat = (double) (location.getLatitude() * 1E6);
int lontitue = (int)lon;
int latitute = (int)lat;
Toast.makeText(getApplicationContext(), "New Lontitue = "+ lontitue +"\n New Latitute = "+ latitute, Toast.LENGTH_LONG).show();
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
You need to add mapview.invalidate(); after your mapController.animateTo(geopoint) like this
GeoPoint geopoint = new GeoPoint(latitute, lontitue);
mapController.animateTo(geopoint);
mapview.invalidate();
That should work!

Categories

Resources