I have written the following code that returns my current location address. But i can get these values only if the my Wifi is switched on manually. but i want to switch on the Gps and get my address from GPS and not from Wifi. Someone please tell me what is to be modified in this code to do so. Following is the code am using to locate my current address. Thanks in advance.
public String myloc()
{
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
String provider = locationManager.getBestProvider(criteria, true);
// Update the GUI with the last known
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null)
{
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
Geocoder gc = new Geocoder(this, Locale.getDefault());
try
{
List<Address> addresses = gc.getFromLocation(lat, lng, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0)
{
Address address = addresses.get(0);
sb.append(address.getAddressLine(0)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getAdminArea()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
}
catch (IOException e)
{
}
}
else
{
latLongString = "No location found";
}
return addressString;
}
It may be helpful to you.
Below is MyLocation.Java file
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(), 60000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
And now used this file in another Main class file
MyLocation myLocation = new MyLocation();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
findCurrentLocation();
}
private void findCurrentLocation() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
String strloc = location.getLatitude() + ","
+ location.getLongitude();
}
}
};
now Toast messge of "strloc".
Thanks,
Nik...
Because you set this :
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
If you leave only
criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
will retrive the best provider as gps, however the code from Nik... is very good for many cases
Related
A year ago I've searched how to get the devices lat,long. I found out in an article here that the correct way is for my activity to implement LocationListener and I've used the code that was provided to achieve it and it worked well.
public Location getLocation() {
LocationManager mLocationManager;
Location mLocation = null;
try {
mLocationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
// getting GPS status
boolean isGPSEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
boolean isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
enableLocationProvider();
} else {
// First get location from Network Provider
if (isNetworkEnabled) {
mLocationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 20000, 1, this);
Log.d("Network", "Network");
if (mLocationManager != null) {
mLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (mLocation != null) {
double lat = mLocation.getLatitude();
double lng = mLocation.getLongitude();
}
}
}
//get the location by gps
if (isGPSEnabled) {
if (mLocation == null) {
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,20000,1, this);
Log.d("GPS Enabled", "GPS Enabled");
if (mLocationManager != null) {mLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mLocation != null) {
double lat = mLocation.getLatitude();
double lng = mLocation.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return mLocation;
}
I've tried to do this now again and used a phone that hasn't been used for a while and I could get the location. By the way when I opened
Google maps
After a few seconda the app located my coordinates. I'm sure that I'm doing something wrong. How can I locate the device's coordinates as efficiently as google maps does it?
The challenge is GPS takes some time to initialize and meanwhile if you try to access the location it will give you a null. So far this is the best approach I've found in Stack Overflow. Its robust and avoid getting a null and ensures a location data in return whenever the GPS is finished initializing
MyLocation class for getting location changes,
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
public 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(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
To receive the location updates override the gotLocation() method which will give you a data once there's a location change.
MyLocation.LocationResult locationResult = new MyLocation.LocationResult() {
#Override
public void gotLocation(Location location) {
//Got the location!
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(getActivity(), locationResult);
I am trying to get the location from the GPS but not able to get it. this is because the location is accessed by the Network provider.
If I am commenting all the code of network provider then the GPS location returns null.
I have tried so much, but unable to resolve this.
If anybody can help then it will be great help for me.
I am using this link for the reference..
https://stackoverflow.com/a/3145655/1395259
Here is my code:
MainActivity.java
package com.example.locationsimple;
import com.example.locationsimple.MyLocation.LocationResult;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
LocationResult locationResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textViewLocation);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationResult = new LocationResult(){
#Override
public void gotLocation(Location location) {
while(true)
{
Log.i("Log", "Inside while loop ");
if(location != null)
{
Log.i("Log", "Here the location is not null");
if(location.getLatitude() !=0.0 || location.getLongitude() != 0.0)
{
if(location.getAccuracy() < 100)
{
Log.i("Log", "Inside while loop BREAKS");
try
{
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, ""+loc, Toast.LENGTH_LONG).show();
textView.setText(loc);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
}
else
{
Log.i("Log", "no Accuracy");
Log.i("Log", "latti"+location.getLatitude()+" Longi "+location.getLongitude()+" Accur "+location.getAccuracy()+location.getProvider());
break;
}
}
}
else
{
Log.i("Log", "Here got the location is null");
break;
}
}
//textView.setText(location.getLatitude()+"::"+location.getLongitude()+"::"+location.getAccuracy()+" Provider "+location.getProvider());
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MainActivity.this, locationResult);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyLocation.java
package com.example.locationsimple;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
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;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
Context mContext;
public boolean getLocation(Context context, LocationResult result)
{
mContext = context;
//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);
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
lm.getBestProvider(criteria, true);*/
//exceptions will be thrown if provider is not permitted.
try
{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex)
{
ex.printStackTrace();
}
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)
{
showSettingsAlert();
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(), 30000);
return true;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("GPS Is Not Enabled");
// Setting Dialog Message
alertDialog.setMessage("Please Enabled Wireless Network And GPS");
// On pressing Settings button
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
// lm.removeUpdates(locationListenerNetwork);
Location net_loc=null;
Location 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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Thanks..
You can use the below service for getting gps.just invoke this service at the begining.
public class MyService extends Service {
LocationManager locationManager;
#Override
public void onCreate() {
//
// TODO Auto-generated method stub
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
/** Criteria for selecting best provider */
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
/** Passing criteria and select only enabled provider */
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
/** calls the Location Listner */
locationManager.requestLocationUpdates(provider, 500, 0,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location)
{
System.out.println("+++++++++++++++++++SASI+++++++++++++++++++++++++++++++++++++++++");
String latLongString, addressString = null;
double lat = 0, lng = 0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
//latLongString = "Lat:" + lat + "\nLong: " + lng;
/** Getting Address */
} else {
latLongString = "No location found";
addressString = "No location found";
}
//System.out.println("###########" + addressString + lat + lng);
SearchDeals.latPoint=location.getLatitude();
SearchDeals.lngPoint=location.getLongitude();
Deals_route.sourcelati=location.getLatitude();
Deals_route.sourcelong=location.getLongitude();
}
#Override
public void onDestroy() {
super.onDestroy();
//
//Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
//Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I've just tested the above code on my device and everything is working smoothly, not sure what is the problem at your end.
Important notes:
Please make sure you have the permission to access GPS location in your manifest file
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
The code may not work properly on the emulator , better test on actual device. if you don't have access to one , please checkout the DMMS Emulator Control to generate location data
Edit:
you need to commit out the Location data related to Network Provider.
and Also remove the textView.setText from your LocationResult object because textView is null. so the fixes:
getLocation(Location location) {
.........
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime() +" "+location.getProvider();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show();
}
and comment out the network code from your MyLocation class
// if(network_enabled)
// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
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(), 35000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.
I'm working on a project in which I need to find nearest places to the mobile device (Example: display a list of hotels ordered by the nearest first.) I want to get the longitude and latitude of the mobile phone. The problem is that I want to get them in a class that is NOT an activity and it doesn't have a OnCreate method (The datasource class which contains all the methods dealing with the database). What should I write? and where exactly should I write it?
Please keep it simple! Thank you :)
The activity would need to pass the context (may require passing the actual activity) to the class. After that you should follow this question as it is essentially a duplicate.
How do I get the current GPS location programmatically in Android?
I use this class to grab location:
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(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
And to use this class, you can do something like
locationResult = new LocationResult() {
public void gotLocation(final Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
};
myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
Even though the GPS is on and network is full sometime i am not able to get the lagitude and latitude values of current location but sometimes i am able to get the values sometimes its showing latitude and longitude as 0....can someone help me.
Here is the code which i am using:
package com.fitness24.my24;
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.scheduleAtFixedRate(new GetLastLocation(), 0, 5000);
return true;
}
public void removeGPS()
{
try {
if(lm != null )
{
timer1.cancel();
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
lm.removeUpdates(locationListenerGps);
locationListenerGps = null;
}
if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
{
lm.removeUpdates(locationListenerNetwork);
locationListenerNetwork = null;
}
lm = null;
}
} catch (Exception e) {
}
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
/////////////////getting current location///////////////////////////
private void getCurrentLocation(){
try {
Log.e("", "showmap location triggered" + Singleton.getSingletonForXml().sLat + ""
+ Singleton.getSingletonForXml().sLng);
LocationResult locationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
if (location != null) {
Singleton.sLat = location.getLatitude();
Singleton.sLng= location.getLongitude();
Log.e("", "showmap location triggered" + Singleton.getSingletonForXml().sLat + ""
+ Singleton.getSingletonForXml().sLng);
if(myLocation != null)
{
myLocation.removeGPS();
Log.i("location", "location acheived and remove gps - inside");
}
}
}
};
myLocation = new MyLocation();
myLocation.getLocation(this, locationResult);
}
I would suggest to try this code, I use this code too, and works like a charm:
package com.fitness24.my24;
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){
System.out.println("gps and/or network disabled");
return false;
}
if(gps_enabled){
System.out.println("gps enabled");
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
System.out.println("network enabled");
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 25000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
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);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Then in your main class:
import com.fitness24.my24.MyLocation.LocationResult;
import android.location.Location;
Then also add this in your main, to call/recieve the gps:
private void locationClick() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
double lat = location.getLatitude();
double lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat+" "+sLng;
Toast.makeText(getBaseContext(), "We got gps location!", Toast.LENGTH_LONG)
.show();
}
}catch (Exception e) {
}
}
};
this locationClick() is on onClick event of my button (the button to call/recieve gps info)
Also, don't forget to add this in your manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
It is Simple,
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
And dont forget to use this Permission
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Add the following permissions in your manifest:
<uses-permission android:name="android.permission.ACCESS_GPS"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>