am trying to create a class that will be used in acquiring the users Location. this class will be utilized by an IntentService in the background.
is there a way to do this without extending Activity or FragmentActivity
in my class.
the code so far looks like below.
import android.app.IntentService;
import android.content.Context;
import static android.content.Context.LOCATION_SERVICE;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
public class LocateMe {
// set loc Listener
LocationManager locationManager;
String update_locid, provider;
double mLon, mLat;
Float accuracy;
int count = 0;
Criteria criteria;
Context context;
IntentService is;
onLocationGot mCallback;
public LocateMe(onLocationGot ints){
is = (IntentService) ints;
// This makes sure that the container service has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (onLocationGot) ints;
} catch (ClassCastException e) {
throw new ClassCastException(ints.toString()
+ " must implement LocateMe.onLocationGot");
}
}
private LocationListener mLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Getting latitude of the current myLocation
double latitude = location.getLatitude();
// Getting longitude of the current myLocation
double longitude = location.getLongitude();
// getting accuracy
accuracy = location.getAccuracy();
// Setting latitude and longitude to be used in the TextView
mLat = latitude;
mLon = longitude;
if (count > 5) {
locationManager.removeUpdates(mLocationListener);
}
count++;
mCallback.foundLocation(mLat, mLon, accuracy);
// finish();
}
public void onProviderDisabled(String provider) {// more work required here
// str = provider;
}
public void onProviderEnabled(String provider) {
// str = provider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
provider = locationManager.getBestProvider(criteria, true);
}
};
// #Override
// public void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// }
public void getLocation() {
// Getting Google Play availability status
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(is.getBaseContext( ));
// Showing status
if (status != ConnectionResult.SUCCESS) { // Google Play Services are not available
// int requestCode = 10;
// Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode);
// dialog.show();
} else {
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) is.getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
//criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location or on editing saved location
if (provider != null) {
requestLocation(locationManager, provider);
} else {
//start wifi, gps, or tell user to do so
}
}
}
public void requestLocation(LocationManager locationManager, String provider) {
if (provider != null) {
locationManager.requestLocationUpdates(provider, 1000, 0, mLocationListener);
} else {
//tell user what has happened
}
}
public interface onLocationGot {
public void foundLocation(double lat, double lon, Float accuracy);
}
}
I suspect that your question is if you can get LocationService in non-activity class.
If so, then read below.
To access system services you need to call this method. Activity extends Context, so it's able to get system services. IntentService also extends Context, so you can use your constructor param to get location service.
Related
I am writhing now simple weather program. I use weather Api and must send location of phone to get weather data. As you understand I don't need precise location, so no need for GPS, noneed for ACCESS_FINE_LOCATION. What I need is - to get my location from NETWORK_PROVIDER. But here starts the problem.
At first I tried to use LocationManager and LocationListener. I enabled my WiFi and location in phone settings. Important thing that I want my application work indoor, so that no need for walking to change coordinates and LocationManager will respond. At first I check last known location.
Location location = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER);
Actually, often it does not work. So I get null as location. Especiall when you turn off location in smartphone settings and after a few minutes turn it on.
OKAY, you don't have lastKnownLocation, then lets get it us. I use requestLocationUpdates() to get current location:
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListener);
Now the magic begins... Sometime (one time in several hours OR several times in a minute) the requestLocationUpdates() works. But most of time it does not react. After many searches in internet I found Google Api, in particular FusedLocationProviderClient class. But again same story happens. But now I could understand that requestLocationUpdates() is not called.
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
I decided to put a button to see does it sends any requestLocationUpdates, but when I click button I have error.
587-673/? E/ANDR-PERF-MPCTL: Invalid profile no. 0, total profiles 0 only
To Summarize, my app simply dont send requestLocationUpdates. And I need just approximate location of my device to get city name, so no need for GPS. Please help me to solve this problem. Thanks.
You can use this class to get Current or Last Known Location if current location is currently not available.
initialize activity in your Manifest.xml
inside application tag
<activity android:name=".LocationFinder"></activity>
start this activity by calling
startActivity(new Intent(getApplicationContext(), LocationFinder.class));
finish();
Now, you can get Location in any other activity by just calling -> LocationFinder.finalAddress
Location and Internet permissions required
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
LocationFinder.java
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
#SuppressLint("MissingPermission")
public class LocationFinder extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private String provider;
public static String finalAddress;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getLoc();
}
public void getLoc() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
if (location == null) {
location = getLastKnownLocation();
}
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
Toast.makeText(this, "Location not available...", Toast.LENGTH_SHORT).show();
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
#SuppressLint("MissingPermission")
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null
|| l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
if (bestLocation == null) {
return null;
}
return bestLocation;
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
//You had this as int. It is advised to have Lat/Loing as double.
double lat = location.getLatitude();
double lng = location.getLongitude();
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
StringBuilder builder = new StringBuilder();
try {
List<Address> address = geoCoder.getFromLocation(lat, lng, 1);
int maxLines = address.get(0).getMaxAddressLineIndex()+1;
for (int i=0; i<maxLines; i++) {
String addressStr = address.get(0).getAddressLine(i);
builder.append(addressStr);
builder.append(" ");
}
finalAddress = builder.toString(); //This is the complete address.
} catch (IOException | NullPointerException e) {
// Handle IOException
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
After getting complete address you can use split method to get country name etc
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
+ "®istration_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();
}
};
I am currently working on a coding project that requires the following:
Map the user's location (GPS) enabled with a button
Hard code a list of GPS points onto a map
Calculate the distance from the user's location to the hard coded GPS points on the map
Currently, I have code concerning the user's location (GPS) with a button:
GPSTracker.java
package com.example.gpstracking;
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();
}
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) {
}
#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;
}
}
My biggest concern is figuring out how to hardcode the gps points into the application. I have found similar code in the following post. As for find the distance, I think using the Location.distanceBetween() will be sufficient. Your help is much appreciated.
How to write GPS coordinates to EXIF data on Android
Try this one.
package com.example.tracker;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
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.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class MainActivity extends FragmentActivity implements LocationListener {
private GoogleMap map;
private static final LatLng ROMA = new LatLng(42.093230818037,
11.7971813678741);
private LocationManager locationManager;
private String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = ((SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map)).getMap();
LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
boolean enabledGPS = service
.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean enabledWiFi = service
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// Check if enabled and if not send user to the GSP settings
// Better solution would be to display a dialog and suggesting to
// go to the settings
if (!enabledGPS) {
Toast.makeText(this, "GPS signal not found", Toast.LENGTH_LONG)
.show();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
Toast.makeText(this, "Selected Provider " + provider,
Toast.LENGTH_SHORT).show();
onLocationChanged(location);
} else {
// do something
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
double lat = location.getLatitude();
double lng = location.getLongitude();
Toast.makeText(this, "Location " + lat + "," + lng, Toast.LENGTH_LONG)
.show();
LatLng coordinate = new LatLng(lat, lng);
Toast.makeText(this,
"Location " + coordinate.latitude + "," + coordinate.longitude,
Toast.LENGTH_LONG).show();
Marker startPerc = map.addMarker(new MarkerOptions()
.position(coordinate)
.title("Start")
.snippet("Inizio del percorso")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Have you tried looking into markers? They're not exactly what you're looking for, but from reading your problem description, it seems like they'll fit your needs.
I have tried following code but not getting current location.
When I manual set location at emulator control then I get such location but not getting current location .I get null location.
How to get current location?
Is there any other way to get current location?
This is my code:
package com.p;
import android.app.Activity;
import android.os.Bundle;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class GooglemapActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
EditText t;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);//true if required
criteria.setBearingRequired(false);//true if required
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locationManager.getBestProvider(criteria, true);
//provider=LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
/*check provder*/boolean statusOfGPS =locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if ( statusOfGPS==true) {
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
} else {
latituteField.setText("Provider is not available");
longitudeField.setText("Provider not available");
}
}
else
{
latituteField.setText("eeeeeeeee");
longitudeField.setText("rrrrrrrrr");
}
}
/* Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latituteField.setText(Double.toString(lat));
longitudeField.setText(Double.toString(lng));
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have added permissions in manifest.xml as below:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
You won't get current location in emulator. You can set them through DDMS, and they will be your current location in case of a emulator.
Please, don't try to get last-known-location, most of the time it's stale and useless. Set up locationListener instead and wait for the location updates. This will get you your current location.
You may use this code to start listing for GPS updates and do something with the data you receive. It also prints messages in the log file for easy debugging. Please, note, this function does not return any results, it only starts listening to GPS. Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere.
private void getGpsData() {
locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "location change:" + location.toString());
String longitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
if( location.hasAccuracy() ) { // good enough?
// do something here with the new location data
....
//
Log.i(TAG, "GPS listener done");
locationManager.removeUpdates(this); // don't forget this to save battery
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, provider + " status:" + status);
}
public void onProviderEnabled(String provider) {
Log.i(TAG, provider + " enabled");
}
public void onProviderDisabled(String provider) {
Log.i(TAG, provider + " disabled");
}
};
Log.i(TAG,"GPS listener started");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}
Do I register a single locationlistener object for both network location and gps location or do I create a separate one for each?
You can use the same listener for both.
When you get the onLocationChanged() or onStatusChanged() callback you can examine the incoming parameters (location or provider) to determine the source of the callback (ie: Network or GPS).
Use the below class for retrieving location. It will choose the best provider and return the latitude and longitude:
package com.test.location;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;
public class LocationPicker implements LocationListener, OnCancelListener{
private Context ctx;
private LocationManager locationMgr;
private boolean stopFlag;
private ProgressDialog dialog;
public LocationPicker(Context ctx) {
this.ctx = ctx;
}
public void retrieveLocation() {
String locCtx = Context.LOCATION_SERVICE;
locationMgr = (LocationManager) ctx.getSystemService(locCtx);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
String provider = locationMgr.getBestProvider(criteria, true);
locationMgr.requestLocationUpdates(provider, 0, 0, this);
Runnable showWaitDialog = new Runnable() {
#Override
public void run() {
while (!stopFlag) {
// Wait for first GPS Fix (do nothing until loc != null)
}
// After receiving first GPS Fix dismiss the Progress Dialog
dialog.dismiss();
}
};
dialog = ProgressDialog.show(ctx, "Please wait...", "Retrieving GPS data...", true);
dialog.setCancelable(true);
dialog.setOnCancelListener(this);
Thread t = new Thread(showWaitDialog);
t.start();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
stopFlag = true;
Toast.makeText(ctx, "Latitude : " + latitude + " Longitude : " + longitude , Toast.LENGTH_LONG).show();
}
locationMgr.removeUpdates(this);
}
#Override
public void onProviderDisabled(String provider) {
// Toast.makeText(ctx, "GPS Disabled", Toast.LENGTH_LONG).show();
//
// Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
// ctx.startActivity(intent);
}
#Override
public void onProviderEnabled(String provider) {
// Toast.makeText(ctx, "GPS Enabled", Toast.LENGTH_SHORT).show();
//
// ctx.startActivity(new Intent(ctx, LocationPickerActivity.class));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onCancel(DialogInterface dialog) {
stopFlag = true;
locationMgr.removeUpdates(this);
}
}
After the creating the above class, just call the below method and it will return the latitude and longitude:::
LocationPicker lp = new LocationPicker(this);
lp.retrieveLocation();
Note: The custom location listener also has progress dialog included in it.