package com.ecsmon.android.core;
import static com.ecsmon.android.constants.Constants.log;
import java.io.IOException;
import java.util.List;
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;
#SuppressLint("NewApi")
public class GPSManager {
private double currentLatitude = 0d;
private double currentLongitude = 0d;
private static Context mCtx;
private Location lastLocationBestProvider = null;
private LocationManager mLocationManager;
private GPSListenerImpl mGPSListener;
private com.ecsmon.android.core.LocationListener mOutListener;
private boolean enabled = false;
private GPSListenerImpl mNETListener;
public GPSManager(Context ctx, com.ecsmon.android.core.LocationListener locationListener) {
mCtx = ctx;
mLocationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
mOutListener = locationListener;
}
/**
* Start location updates
*/
public void start() {
log("#### Started tracking");
lastLocationBestProvider = getLastLocationFromBestProvider();
if (lastLocationBestProvider != null) {
currentLatitude = lastLocationBestProvider.getLatitude();
currentLongitude = lastLocationBestProvider.getLongitude();
log("lat" + currentLatitude + " long " + currentLongitude);
} else {
log("last loaction is null");
}
// mGPSListener = new GPSListenerImpl("GPS");
mNETListener = new GPSListenerImpl("NET");
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 1, mNETListener);
// mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 1, mGPSListener);
}
private class GPSListenerImpl implements LocationListener {
private String name = "";
public GPSListenerImpl(String name) {
log("listener created" + name);
this.name = name;
}
public void onLocationChanged(Location loc) {
log("######### LOCATION CHANGED CALLED!!!!!!!!!!!!!!!!! ##############");
if (loc != null) {
log("######### location changed " + loc.getAccuracy());
currentLatitude = loc.getLatitude();
currentLongitude = loc.getLongitude();
mOutListener.update(currentLongitude, currentLatitude);
} else {
log("location is null");
}
}
public void onProviderDisabled(String provider) {
log("provider disabled > " + name);
}
public void onProviderEnabled(String provider) {
log("provider enabled > " + name);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
log("status changed");
}
}
/**
* Return last location saved in phone or null
*
* #return Location
*/
public Location getLastLocationFromBestProvider() {
if (!enabled) {
return null;
}
try {
LocationManager lm = (LocationManager) mCtx.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
String strLocationProvider = lm.getBestProvider(criteria, true);
Location location = lm.getLastKnownLocation(strLocationProvider);
if (location != null) {
return location;
}
return null;
} catch (Exception e) {
log(e.getMessage());
return null;
}
}
/**
* Returns human readable address from longitude and latitude
*
* #param latitude
* #param longitude
* #return
*/
public String getAddress(Double latitude, Double longitude) {
if (!enabled) {
return null;
}
String m = "";
try {
if (!Geocoder.isPresent()) {
return null;
}
Geocoder geo = new Geocoder(mCtx);
List<Address> addresses = geo.getFromLocation(latitude, longitude, 1);
if (addresses.isEmpty()) {
return null;
} else {
if (addresses.size() > 0) {
m = addresses.get(0).getFeatureName() + ", " + addresses.get(0).getLocality() + ", "
+ addresses.get(0).getCountryName();
}
}
} catch (IOException ie) {
log("No connection.");
return null;
} catch (Exception e) {
log("Can't read adress from this cordinates : lat = " + latitude + " long " + longitude); //
return null;
}
return m;
}
/**
* Removes all location updates
*/
public void stop() {
try {
mLocationManager.removeUpdates(mGPSListener);
mLocationManager.removeUpdates(mNETListener);
} catch (Exception e) {
}
}
}
This is my main class for fetching current location and onLocationChanged never gets called. Im testing on emulator, and sending mock longitude and latitude via Emulator Control. Please Help this is driving me mad :(
Stefan was right. You need to do 2 things.
Grant access to mock location. As of now this needs to be specified in a special manifest file under src/debug/AndroidManifest.xml. Create that xml and add this permission to it:
uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"
Make sure your location manager is hooked on to the GPS provider and not the network provider. That information can be found here:
http://developer.android.com/guide/topics/location/strategies.html#MockData
You can change the GPS location values of emulator using Emulator control. By doing this (onLocationChanged method will work) you can test your application in Emulator
Problem is on emulator it wont work, but on real device it found my location in sec
In my case, the problem was for the update frecuency of the accelerometer and magnetic_field sensors. Only changed "SensorManager.SENSOR_DELAY_FASTEST" or SensorManager.SENSOR_DELAY_GAME" to "SensorManager.SENSOR_DELAY_NORMAL" and it´s worked correctly.
Curiously, the frecuency of the GPS sensor can be "SensorManager.SENSOR_DELAY_FASTEST" and don´t have any problem.
Related
I want to get my current latitude and longitutude each 30 second but I can get same coordinates in each 30 second its doesn't change I use Gps services class it is below.How can I change location when I moved to device.
public class GPSService extends Service implements LocationListener {
// saving the context for later use
private final Context mContext;
// if GPS is enabled
boolean isGPSEnabled = false;
// if Network is enabled
boolean isNetworkEnabled = false;
// if Location co-ordinates are available using GPS or Network
public boolean isLocationAvailable = false;
// Location and co-ordinates coordinates
Location mLocation;
double mLatitude;
double mLongitude;
// Minimum time fluctuation for next update (in milliseconds)
private static final long TIME = 30000;
// Minimum distance fluctuation for next update (in meters)
private static final long DISTANCE = 20;
// Declaring a Location Manager
protected LocationManager mLocationManager;
public GPSService(Context context) {
this.mContext = context;
mLocationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
}
/**
* Returs the Location
*
* #return Location or null if no location is found
*/
public Location getLocation() {
try {
// Getting GPS status
isGPSEnabled = mLocationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS enabled, get latitude/longitude using GPS Services
if (isGPSEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If we are reaching this part, it means GPS was not able to fetch
// any location
// Getting network status
isNetworkEnabled = mLocationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this);
if (mLocationManager != null) {
mLocation = mLocationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
mLongitude = mLocation.getLongitude();
isLocationAvailable = true; // setting a flag that
// location is available
return mLocation;
}
}
}
// If reaching here means, we were not able to get location neither
// from GPS not Network,
if (!isGPSEnabled) {
// so asking user to open GPS
askUserToOpenGPS();
}
} catch (Exception e) {
e.printStackTrace();
}
// if reaching here means, location was not available, so setting the
// flag as false
isLocationAvailable = false;
return null;
}
/**
* Gives you complete address of the location
*
* #return complete address in String
*/
public String getLocationAddress() {
if (isLocationAvailable) {
Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());
// Get the current location from the input parameter list
// Create a list to contain the result address
List<Address> addresses = null;
try {
/*
* Return 1 address.
*/
addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1);
} catch (IOException e1) {
e1.printStackTrace();
return ("IO Exception trying to get address:" + e1);
} catch (IllegalArgumentException e2) {
// Error message to post in the log
String errorString = "Illegal arguments "
+ Double.toString(mLatitude) + " , "
+ Double.toString(mLongitude)
+ " passed to address service";
e2.printStackTrace();
return errorString;
}
// If the reverse geocode returned an address
if (addresses != null && addresses.size() > 0) {
// Get the first address
Address address = addresses.get(0);
/*
* Format the first line of address (if available), city, and
* country name.
*/
String addressText = String.format(
"%s, %s, %s",
// If there's a street address, add it
address.getMaxAddressLineIndex() > 0 ? address
.getAddressLine(0) : "",
// Locality is usually a city
address.getLocality(),
// The country of the address
address.getCountryName());
// Return the text
return addressText;
} else {
return "No address found by the service: Note to the developers, If no address is found by google itself, there is nothing you can do about it.";
}
} else {
return "Location Not available";
}
}
/**
* get latitude
*
* #return latitude in double
*/
public double getLatitude() {
if (mLocation != null) {
mLatitude = mLocation.getLatitude();
}
return mLatitude;
}
/**
* get longitude
*
* #return longitude in double
*/
public double getLongitude() {
if (mLocation != null) {
mLongitude = mLocation.getLongitude();
}
return mLongitude;
}
/**
* close GPS to save battery
*/
public void closeGPS() {
if (mLocationManager != null) {
mLocationManager.removeUpdates(GPSService.this);
}
}
/**
* show settings to open GPS
*/
public void askUserToOpenGPS() {
AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
mAlertDialog.setTitle("Location not available, Open GPS?")
.setMessage("Activate GPS to use use location services?")
.setPositiveButton("Open Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
})
.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
/**
* Updating the location when location changes
*/
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
#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;
}
}
and I call getLocation method for Myclass
double latitudem2, longitudem2;
String cnvrt_latitude2,cnvrt_longitude2;
if (mGPSService2.isLocationAvailable == false) {
cnvrt_latitude2 = "0";
cnvrt_longitude2 = "0";
// Or you can continue without getting the location, remove the return; above and uncomment the line given below
// address = "Location not available";
} else {
mGPSService2.getLocation();
// Getting current location co-ordinates
latitudem2 = mGPSService2.getLatitude();
longitudem2 = mGPSService2.getLongitude();
//Toast.makeText(getApplicationContext(), "Latitude:" + latitudem + " | Longitude: " + longitudem, Toast.LENGTH_LONG).show();
cnvrt_latitude2 = String.valueOf(latitudem2);
cnvrt_longitude2 = String.valueOf(longitudem2);
}
I used a different way. I think you should use Google play.
dependencies {
..
compile 'com.google.android.gms:play-services:8.4.0'
..
}
and in your activity:
private void initGoogleClient() {
googleClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
and then register your app:
LocationRequest req = new LocationRequest();
req.setInterval(60 * 60 * 1000);
req.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(googleClient, req, this);
You can change the priority according to your requirements.
Don't forget to implement the listeners in your Activity
public class MainActivity extends AppCompatActivity
implements GoogleApiClient.OnConnectionFailedListener,
GoogleApiClient.ConnectionCallbacks,
LocationListener {
...
}
I made something similar to know UV index according to the current position. You can give a look at my post.
I know it is a common question and has been answered a number of times... But I am looking for an answer to a specific problem.
I have written a method which is required to return current lat/long as string. The code goes like this:
public class LibraryProvider {
public String basicMethod(String string) {
String text = string;
LocationManager locationManager;
String provider;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
text = "Provider " + provider + " has been selected.";
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
text = text + "\n" + "lat: " + String.valueOf(lat);
text = text + "\n" + "lng: " + String.valueOf(lng);
} else {
text = "Location not available";
}
return text;
}
}
However, the android studio is not allowing this.get System Service:
cannot resolve Method getSystemService(java.lang.String)
I am new to android and not clear about context and intents... I think the problem has something to do with it.
(edited)
the code i was using to load the above class is as under
private final class ServiceHandler extends android.os.Handler {
public ServiceHandler(Looper looper){
super(looper);
}
public void handleMessage(Message msg){
dynamicClassLoader();
}
String text;
private void dynamicClassLoader(){
final String apkFile =Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/apkFile.apk";
String className = "com.va.android.level2.lib.LibraryProvider";
final File optimisedDexOutputPath = getDir("outdex", 0);
DexClassLoader classLoader = new DexClassLoader(apkFile,optimisedDexOutputPath.getAbsolutePath(),null,getClassLoader());
try{
Class loadedClass = classLoader.loadClass(className);
// LibraryInterface lib = (LibraryInterface) loadedClass.newInstance();
// lib.basicMethod("hello");
Object obj =(Object)loadedClass.newInstance();
Method method = loadedClass.getMethod("basicMethod", String.class);
text = (String) method.invoke(obj,"added method");
showOutput(text);
} catch (Exception e){
e.printStackTrace();
}
}
private void showOutput(final String str){
mServiceHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MyService.this,str, Toast.LENGTH_LONG).show();
}
});
}
}
earlier it was working, but now it is raising some exception at loadedClass.newInstance(); .....i think i need to pass the context ...but how??
Try get Activity Context reference in custom class constructor and use it ;
public class LibraryProvider {
private Context context;
public LibraryProvider(Context context){
this.context=context;
}
}
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
You need a Context to call getSystemService(...).
Actually you are calling it from "this" that is not a class that has a Context.
try this
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
Log.d("DEBUG",location.toString());
double lat = location.getLatitude();
double lon = location.getLongitude();
}
};
try this
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
see this link on how to get current location in Android
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.
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();
}
};
import android.app.Activity;
public class LocationTracking extends Activity {
Button btnShowLocation;
Button refresh;
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_tracking);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
refresh = (Button) findViewById(R.id.refresh);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(LocationTracking.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
((TextView)findViewById(R.id.latitude)).setText(Double.toString(latitude));
((TextView)findViewById(R.id.longitude)).setText(Double.toString(longitude));
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
refresh.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((TextView)findViewById(R.id.latitude)).setText("");
((TextView)findViewById(R.id.longitude)).setText("");
}
});
}
}
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;
}
}
i found this gps tracking activity on the net i tried it already and it works perfectly but i encountered a problem later on.when i start a new activity it stop on running what i want to do is for it not to stop even if i start i new activity example if someone is calling or im texting the gps tracking will still track my location where did i make my mistake?
use this code, registered the LocationManager in onchangeLocation() method.
public class NewLocationListener implements android.location.LocationListener {
private final static String TAG = "LocationListener";
private Context context = null;
private LocationManager locationManager = null;
private double latitude = 0.0;
private double longitude = 0.0;
/*public String newlatitude=null;
public String newlongitude=null;*/
private Location gpslocation=null;
public void setDefault() {
Log.v(TAG + ".setDefault", "GPS Co-ordinates initialised");
latitude = 0.0;
longitude = 0.0;
}
public NewLocationListener(Context ctx) {
Log.v(TAG + ".LocationListener", "LocationListener constructor called");
context = ctx;
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void onProviderDisabled(String provider) {
Log.v(TAG + ".onProviderDisabled", "onProviderDisabled method called");
}
public void onProviderEnabled(String provider) {
Log.v(TAG + ".onProviderEnabled", "onProviderEnabled method called");
}
public void onLocationChanged(Location location) {
gpslocation=location;
Log.v(TAG + ".onLocationChanged", "onLocationChanged method called");
//Toast.makeText(context, "onLocationChanged called", Toast.LENGTH_SHORT).show();
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (gpslocation != null) {
setLocationCoordinates(gpslocation);
} else {
Log.v(TAG + ".onLocationChanged", "couldn't get gps using onLocationChange");
getLastKnownLocation();
}
}
public void setLocationCoordinates(Location location) {
try {
double latNew = (location.getLatitude());
double lonNew = (location.getLongitude());
if (latNew != 0.0 && lonNew != 0.0) {
Log.v(TAG + ".onLocationChanged", "New location co-ordinates are not 0");
/* setLatitude(latNew);
setLongitude(lonNew);*/
/*
* latitude = latNew; longitude = lonNew;
*/
String newlatitude=Double.toString(latNew);
String newlongitude=Double.toString(lonNew);
Log.v(TAG, "new latitude is" + newlatitude+" new longitude is" + newlongitude);
//Toast.makeText(context, "lat: " + newlatitude+" lon: " + newlongitude, Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(context, "we got 0.0 value ", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged", "we got 0.0 value ");
}
} catch (Exception e) {
Log.v(TAG + ".onLocationChanged.Exception", "Exception is " + e);
}
}
public void getLastKnownLocation() {
Location location = locationManager.getLastKnownLocation(getBestProvider());
gpslocation=location;
if (gpslocation != null) {
//Toast.makeText(context, "LastKnownLocation called", Toast.LENGTH_SHORT).show();
setLocationCoordinates(gpslocation);
} else {
//Toast.makeText(context, "couldn't get LastKnownLocation", Toast.LENGTH_SHORT).show();
Log.v(TAG + ".onLocationChanged","couldn't get gps using lastKnownLocation");
}
}
public String getBestProvider() {
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
criteria.setAccuracy(Criteria.NO_REQUIREMENT);
String bestProvider = locationManager.getBestProvider(criteria, true);
return bestProvider;
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.v(TAG + ".onStatusChanged", "onStatusChanged method called");
}
public double getLatitude() {
if (gpslocation != null) {
latitude = gpslocation.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (gpslocation != null) {
longitude = gpslocation.getLongitude();
}
return longitude;
}