Finding the users location - android

I am developing an android application. I need to find the location of the user as soon as he/she logs in to the application. I do not want maps to be displayed, the location should be identified without the user's knowledge. Is it possible to do this using the Google maps API? or is there any other way to do this?
Thanks

The best way to do this is to use the PASSIVE location provider like so:
LocationManager lm = (LocationManager)yourActivityContext.getSystemService(Context.LOCATION_SERVICE);
Location lastKnown = lm.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
This returns the last known location received by the operating system, so this may be stale, but you can check when the location was retrieved, and by which provider by querying the location object.
In conclusion, the user will have no idea that you've gotten a location except that your app will require the proper location permission(s).

Try this,
protected LocationManager locationManager;
Context context;
public String gps_loc;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 10, new MyLocationListener());
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
gps_loc = String.format("%1$s" +"-"+"%2$s",location.getLongitude(), location.getLatitude());
Toast.makeText(Clockin.this, gps_loc, Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(class.this, "Provider status changed", Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(class.this,"Provider disabled by the user. GPS turned off",Toast.LENGTH_SHORT).show();
final AlertDialog alertDialog = new AlertDialog.Builder(class.this).create();
alertDialog.setTitle("Activate GPS...");
alertDialog.setButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
});
alertDialog.show();
}
public void onProviderEnabled(String s) {
Toast.makeText(class.this,"Provider enabled by the user. GPS turned on", Toast.LENGTH_SHORT).show();
}
}

Related

How do i get my current location without GPS?

I want to get my current latitude and longitude using Mobile network provider, not GPS. AKA it should work without GPS with just your sim card. i have found many tutorials online claiming they find location with gps or network. however, they all seem to use GPS only! here or here and also here i don't want last knows location, as i don't wish to use GPS
Try This Code you can get current location without opening GPS
btnNWShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
} else {
showSettingsAlert("NETWORK");
}
}
});
Do it via Location Manager.
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
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.NETWORK_PROVIDER, 0, 0, locationListener);

Android Location Service - battery usage

I'm developing an app which uses the location service from the start. My phone (Sony Z3 Compact) has a list of apps which used the location service in the location settings menu. It has each app with a "battery usage" message, like low battery usage, high battery usage etc. My app is listed as "High battery usage". Other apps which use location data like Tinder has it as "low battery usage".
I'd like to know what causes this and what's the best way to save battery. I see that each location provider has a "battery usage" data. Does that mean if I only use network provider as opposed to GPS provider I get the "low battery usage" stamp?
Or does it dependent on requesting location updates? Because I need the location only once, however I might want to check if the user has moved, for that I'd need to turn location updates on.
Any ideas regarding this?
Here is the service I'm using:
public class LocationTracker2 extends Service implements LocationListener {
protected Context context;
protected LocationManager locationManager;
protected OnLocationChanged event;
protected Location currentLocation;
public interface OnLocationChanged {
public void onLocationChanged(double latitude, double longitude);
}
public LocationTracker2(Context context, OnLocationChanged event) {
this.context = context;
this.event = event;
locationManager = (LocationManager)context.getSystemService(LOCATION_SERVICE);
}
public boolean canGetLocation() {
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
return (isGPSEnabled || isNetworkEnabled);
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
// 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);
context.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();
}
public Location getCurrentLocation() {
if(currentLocation != null) return currentLocation;
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
if(bestLocation != null) {
currentLocation = bestLocation;
this.event.onLocationChanged(currentLocation.getLatitude(), currentLocation.getLongitude());
}
return currentLocation;
}
public void startLocationUpdates() {
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
locationManager.requestLocationUpdates(bestProvider, 60000, 10, this);
}
public void stopLocationUpdates() {
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
this.currentLocation = location;
this.event.onLocationChanged(this.currentLocation.getLatitude(), this.currentLocation.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 intent) {
return null;
}
}
When your app is using the GPS provider, it will be listed as High Usage app. The network provider will be listed as low usage.If you will be using the GPS provider for only one point, you will be listed as High Usage, but for a short period.
I can suggest two alternatives for you:
First try to use the Passive Provider, if another app is using the location services at the moment you will receive their updates as well but the system will list them as the App who uses the battery.
Use the Google play location client, it will list the battery usage on Google Play Services instead of on you.

Unable to find user location using GPS

public class LocationtesterActivity extends Activity {
/** Called when the activity is first created. */
LocationManager locManager;
// LocationListener locListener;
Button b;
String provider;
TextView lat, alt, longi;
// Here i am first checking if both GPS and network options are enabled in Lovation and Security Settings or not.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button) findViewById(R.id.button1);
lat = (TextView) findViewById(R.id.lattitude);
alt = (TextView) findViewById(R.id.altitude);
longi = (TextView) findViewById(R.id.longitude);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = locManager.getBestProvider(criteria, true);
System.out.println("best provider is :" + provider);
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| !locManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
System.out.println("in provider enablement");
createGpsDisabledAlert();
}
else {
System.out.println("in location update request");
locManager.requestLocationUpdates(provider, 0, 0,
new MyLocationListener());
}
}
// for displaying the Dialogue Box
// if GPS or network not enabled
// and also taking to location and security screen
private void createGpsDisabledAlert() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(
"Your GPS or network provider is disabled! Would you like to enable it?")
.setCancelable(false)
.setPositiveButton("Enable provider",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
showGpsOptions();
}
});
builder.setNegativeButton("Do nothing",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGpsOptions() {
Intent gpsOptionsIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gpsOptionsIntent, 5);
}
// //////ends/////
// Code to check whether user enabled GPS and Network provider in settings
// if not then show the dialogue box again
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 5 && resultCode == 0) {
if (!locManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
createGpsDisabledAlert();
// Toast.makeText(this,
// "provider not enabled. Click the button for settings",
// 2000).show();
} else {
Intent i=new Intent(this, LocationtesterActivity.class);
startActivity(i);
Toast.makeText(this, "User has enabled the provider", 1000)
.show();
}
}
}
// Method to display the current location
protected void showCurrentLocation() {
Location location = locManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(LocationtesterActivity.this, "no last known location", 1000).show();
}
}
// Inner class for LocationListener
private class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
System.out.println("in location changed");
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
lat.setText("" + location.getLatitude());
longi.setText("" + location.getLongitude());
// alt.setText("" + location.getAltitude());
Toast.makeText(LocationtesterActivity.this, message,
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(LocationtesterActivity.this,
"Provider status changed",
Toast.LENGTH_LONG).show();
}
public void onProviderDisabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String s) {
Toast.makeText(LocationtesterActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
I am using the above code to find the User Location.
1.I am getting always GPS as the best provider according to my criteria but that is fine to me.
2.Thing is that why am i not able to get any location values ?
Even with Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); i am not getting any thing.
Please help me in getting the location values.
GPS take some time due to slow and not available inside the building .You just check it outside the building.
And
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); only works if once GPS get any location previously.
Two things,
Have u set "android.permission.ACCESS_FINE_LOCATION" permission in manifest file ??
clear all data of Google map application and then try to load map for get current location on map, If Google map give your current location then your application can fetch current location.
Its good habit to use best criteria for fetching location.
sometimes devices can not read current location. I also face this problem but at that time i check Google Map / Direction application and reset my GPS.

Android :How can i check whether GPS is working in my android device or not?

i am working in android. i am designing an application which is based on GPS location of my device.
Whenever i press any event key in my application i need to check whether my device is getting GPS location all the time or not.
Please help me for this. you may provide weblink for this.
Thank you in advance.
You should use this type of code:-
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = mlocManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
myLongitude = location.getLongitude();
myLatitude= location.getLatitude();
}
else
{
myLongitude =0;
myLatitude= 0;
}
LocationListener mlocListener;
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Log.v("Checkin_Inspect_activity","cordintes of this place = "+myLatitude+" "+myLongitude);
and design you class like this:-
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
myLatitude= loc.getLatitude();
myLongitude=loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
// Toast.makeText( getApplicationContext(),"Gps Disabled", Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
// Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
you can use the LocationListener class which will give the location detail whenever the location was update
here is the simple snippet of LocationListener
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
Edited
you can check the provider for location for gps like this way
if (manager.isProviderEnabled( LocationManager.GPS_PROVIDER ) ) {
// do something
}else{
// do another thing
}
check out this tutorial link
http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/

LocationManager will not return destination

I created this earlier on today, but it is not working. Location manager returns null, and I've even implemented the listener. Any ideas to the problems. thanks.
Edited:
I think this line is the problem
Location location = locationManager.getLastKnownLocation(provider);
Basically, if location is null, it will go into the else part of the if statement below it. Every time I compile the code, it will go into the else statement meaning it location is not updating.
public class Activity1 extends Activity implements LocationListener {
/** Called when the activity is first created. */
JoshTwoActivity main;
Activity2 two;
boolean checkTick = false;
String locationplace = "";
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println(provider);
System.out.println(locationManager.getProviders(criteria, false));
System.out.println(locationManager.getProvider("network"));
System.out.println(locationManager.getAllProviders());
Location location = locationManager.getLastKnownLocation(provider);
System.out.println(locationManager.isProviderEnabled(provider));
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
} else {
System.out.println("Provider not available");
System.out.println("Provider not available");
}
}
/* 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) {
int lat = (int) (location.getLatitude());
int lng = (int) (location.getLongitude());
System.out.println(String.valueOf(lat));
System.out.println(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#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, "Disenabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
getLastKnownLocation() returns a location with the last known location fix for a provider. If the provider returns null, the provider has never had a location fix. It doesn't mean the provider is not available.
Once you call getLastKnownLocation() you should check to see if the results are accurate or recent enough for your purpose. If not you should request location updates using requestLocationUpdates().
This blog post contains everything you need to know about writing code using location providers.
http://android-developers.blogspot.com/2011/06/deep-dive-into-location.html
Ok my first guess is that you are not giving location fix via command line or by using eclipse DDMS perpective. If this is problem go open DDMS perpecive and give latitude and longtiude you want and send it. So location will not be null from now on if this is the problem.
The following link may help you in understanding how to use emulator in finding the location. The last section of this page has that information.
http://developer.android.com/guide/topics/location/obtaining-user-location.html

Categories

Resources