Hi to all im new to android and i have a small problem and i would really appreciate if someone can help me
first im trying to show all available location providers and its not working and 2nd when ever i run the it i don't get any location information from the best available provider (i have my wifi and network providers on)
thanks in advance
package com.paad.whereami;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.content.Context;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
public class WhereAmI extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(context);
boolean enabledOnly = true;
List<String> providers = locationManager.getProviders(enabledOnly);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
criteria.setSpeedRequired(true);
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 2000, 1,
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) {
String latLongString;
TextView myLocationText;
myLocationText = (TextView)findViewById(R.id.myLocationText);
String addressString = "No address found";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Lat:" + lat + "\nLong:" + lng;
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude, longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i < address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
sb.append(address.getLocality()).append("\n");
sb.append(address.getPostalCode()).append("\n");
sb.append(address.getCountryName());
}
addressString = sb.toString();
} catch (IOException e) {}
} else {
latLongString = "No location found";
}
myLocationText.setText("Your Current Position is:\n" +
latLongString + "\n" + addressString);
}
}
I had also same problem before, after searching a lot...came to solution and makes it possibale to get instant location of device through following code...actuallu we can not have gps responce instantly so we can have our location on the basis of cell-tower or wifi. so enable one of them to get instant location of your device..
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.leopard_screen);
FindLocation(this);
}
public void FindLocation(Context context) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (network_enabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0,
locationListenerNetwork);
Log.i("########## Network provider is enabled", "Network Provider");
} else {
Toast.makeText(LeopardScreen.this,
"Network provider is not enabled", 2000);
}
if (gps_enabled) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListenerGPS);
Log.i("########## GPS provider is enabled", "GPS Provider");
} else {
Toast.makeText(LeopardScreen.this, "GPS provider is not enabled",
2000);
}
if(!network_enabled && !gps_enabled) {
currentLocation = getMyLastKnownLocation();
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Both location provider disabled",
"getMylastKnownLocation = "+String.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(LeopardScreen.this,"LastKnownLocation\n"+String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 3000).show();
Intent intent = new Intent(LeopardScreen.this, mainActivity.class);
startActivity(intent);
}
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
updateLocation(location);
handler.removeCallbacks(runnable);
Log.i("######## Inside FindLocation", "Inside FindLocation");
Toast.makeText(
LeopardScreen.this,"Network Location \n"+
String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
updateLocation(location);
Log.i("########## Inside onLocationChangedGPS", String
.valueOf(currentLatitude)
+ " : " + String.valueOf(currentLongitude));
Toast.makeText(
LeopardScreen.this,
"GPS Location \n" + String.valueOf(currentLatitude) + "\n"
+ String.valueOf(currentLongitude), 5000).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
};
public Location getMyLastKnownLocation () {
Location locNetwrok = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Location locGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(locNetwrok != null)
return locNetwrok;
else if(locGPS != null)
return locGPS;
return null;
}
void updateLocation(Location location) {
currentLocation = location;
currentLatitude = currentLocation.getLatitude();
currentLongitude = currentLocation.getLongitude();
Log.i("######## Inside LeopardScreen locationChanged",
"locationChanged");
}
Don't Forgot to add in Menifeast
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET"/>
Related
I am trying to get the location from the best provider. I have enabled the GPS. Also, when I am printing the latitude and longitude, I am getting it from the Network provider.
My question is:
If GPS is enabled, then I want to search for 30 seconds for the location via GPS. After that, if I got the accuracy below 200 meters, then I use that. If the accuracy goes beyond 200 meters, then I search again and get started from the network provider.
After that, I compare both accuracies and take the data of the provider which is more accurate.
Here is my code:
LocationUtil.java
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class LocationUtil
{
Activity activity;
Location location;
public LocationUtil(Activity activity)
{
this.activity = activity;
}
public int getLogitudeE6()
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lg = (int) (((double) location.getLongitude()) * 1E6);
System.out.println("Longitude :: " + lg);
return lg;
}
public int getLatitudeE6()
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
int lt = (int) (((double) location.getLatitude()) * 1E6);
System.out.println("Latitude :: " + lt);
return lt;
}
public double getLogitude(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getLongitude();
}
public double getLatitude(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getLatitude();
}
public double getAccuracy(Location location)
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location == null)
{
location = lm
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
this.location = location;
}
return location.getAccuracy();
}
public double getLogitude()
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
this.location = location;
}
return location.getLongitude();
}
public double getLatitude()
{
if (location == null)
{
LocationManager lm = (LocationManager) activity
.getSystemService(Context.LOCATION_SERVICE);
Location location = lm
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
this.location = location;
}
return location.getLatitude();
}
}
CaptureMain.java
import java.util.Timer;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class CaptureMain extends Activity implements LocationListener {
/** Called when the activity is first created. */
TextView txtNewLocation;
String strLatBack, strLongBack, strLatitude, strLongitude,strAccuracy;
LocationUtil locationUtil;
Location location;
LocationManager lm;
String bestProvider;
Timer timer;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtNewLocation = (TextView) findViewById(R.id.txtLocation);
locationUtil = new LocationUtil(this);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
try {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
bestProvider = lm.getBestProvider(criteria, false);
Log.i("Log", "Best provider is : "+bestProvider);
strLatitude = String.valueOf(locationUtil.getLatitude(location));
strLongitude = String.valueOf(locationUtil.getLogitude(location));
strAccuracy = String.valueOf(locationUtil.getAccuracy(location));
txtNewLocation.setText("Latitude :" + strLatitude + ", Longitude :"
+ strLongitude + " , Accuracy "+ strAccuracy);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onLocationChanged(Location location) {
System.out.println("On Location change called:: ");
if (location != null) {
this.location = location;
}
strLatitude = String.valueOf(locationUtil.getLatitude(location));
strLongitude = String.valueOf(locationUtil.getLogitude(location));
strAccuracy = String.valueOf(locationUtil.getAccuracy(location));
if (strLatitude.equals("") || strLongitude.equals("")) {
txtNewLocation.setText("Locating current position..");
} else {
txtNewLocation.setText("Latitude :" + strLatitude + ", Longitude :"
+ strLongitude + " , Accuracy "+ strAccuracy);
}
}
#Override
protected void onStart() {
super.onStart();
startListening();
}
#Override
protected void onResume() {
super.onResume();
startListening();
}
#Override
protected void onPause() {
super.onPause();
stopListening();
}
#Override
protected void onDestroy() {
super.onDestroy();
stopListening();
finish();
}
private void stopListening() {
if (lm != null)
lm.removeUpdates(this);
}
private void startListening() {
lm.requestLocationUpdates(bestProvider, 0, 0, this);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Added permission in manifest:
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
I have not studied your algorithm in detail, but 200m is not a good threshold for GPS.
horicontal accuracy should be under 50 m.
only GPS has attribute course and altitude(i am not 100% sure) and speed . check for a valid altitude and course, too.
Course (and speed) is only valid if device moves.
But can you not just simply query the type of location provider? (GPS)
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 want to get current longitude and latitude as int
So I use this code
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this);
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
}
// don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled) {
....Notify
}
if (gps_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
if (network_enabled) {
if (location != null) {
longitude =(int) (location.getLongitude()*1e6);
latitude = (int) (location.getLatitude()*1e6);
String accuracy = "Accuracy: " + location.getAccuracy();
}
}
locationManager.removeUpdates(this);
Unfortunately longitude and latitude are always null.
I have all permission needed in the manifest.
How can I fix this issue?
Well this is what i use for location listener
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class LocationUtils implements LocationListener{
Context context;
private String provider;
private LocationManager locationManager;
private String latitude="no value";
private String longitude="no value";
public LocationUtils(Context context) {
this.context=context;
// Get the location manager
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
latitude="no value";
longitude="no value";
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
/*Toast.makeText(context, "Provider " + provider + " has been selected.",
Toast.LENGTH_SHORT).show();*/
// System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
/*Toast.makeText(context, "Location not available",
Toast.LENGTH_SHORT).show();*/
}
}
#Override
public void onLocationChanged(Location location) {
double lat = (double) (location.getLatitude());
double lng = (double) (location.getLongitude());
latitude = lat + "";
longitude = lng + "";
/* Toast.makeText(context, " lat: "+lat +" Long:"+lng,
Toast.LENGTH_SHORT).show(); */
}
#Override
public void onProviderDisabled(String provider) {
//Toast.makeText(context, "Disabled provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
//Toast.makeText(context, "Enabled new provider " + provider,
// Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public String getLatitude() {
return latitude;
}
public String getLongitude() {
return longitude;
}
}
Now in your activity u can get
LocationUtils appLocationManager = new LocationUtils(getContext());
String latitude = appLocationManager.getLatitude();
String longitude = appLocationManager.getLongitude();
Also add
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>
in your manifest file
First check the GPS enabled in your device.
Check all the permissions included in the manifest
You are fetching the last known location using the GPS provider so remove that line and fetch the location individually for both the provider(There should be possible that your GPS is not available at that time so you did not get the location and you are fetching the last known location using the GPS so it can be null and if location will be null then it will not goes inside the conditions like if(network_enabled) and if(gps_enabled).).
In short check the Last known location of GPS if it is null then try to get the location using the Location provider and use that location.
public class SMS_Service extends Service {
private final String LOGTAG = "SMS_Service";
String latLongString;
String addressString;
double altitude;
int LAC;
int mcc = 0;
int mnc = 0;
String pn_no;
Altitude_Details ld = new Altitude_Details();
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.e(LOGTAG, "created");
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Log.e(LOGTAG, "destroyed");
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
Log.e(LOGTAG, "started");
SmsManager sms = SmsManager.getDefault();
// get phone number from shared preference
SharedPreferences default1 = getSharedPreferences("Device",
MODE_WORLD_WRITEABLE);
pn_no = default1.getString("Phone_NO", "");
Log.e("phone_no in sms service", pn_no);
String From = intent.getStringExtra("From");
String Msg = intent.getStringExtra("Msg"); // get message from intent
Log.e("ON start:", "" + From);
Log.e("ON start:", "" + Msg);
String number = From.substring(7, 11);
Log.e("ON start: SUBSTRING", "" + number);
// check msg for Location keyword match or not
if (Msg.equals("LOCATION") && pn_no.equals(number)) {
Log.e("location:", "Location found");
TelephonyManager tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = tel.getNetworkOperator();
// find MNC and MCC
if (networkOperator != null) {
mcc = Integer.parseInt(networkOperator.substring(0, 3));
mnc = Integer.parseInt(networkOperator.substring(3));
Log.e("MCC", "" + mcc);
Log.e("MNC", "" + mnc);
}
// find LAC for GSM
if (tel.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
final GsmCellLocation location = (GsmCellLocation) tel
.getCellLocation();
if (location != null) {
LAC = location.getLac();
Log.e("cell location", "LAC: " + location.getLac()
+ " CID: " + location.getCid());
}
}
LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
// update method return latest location
updateWithNewLocation(location);
// location change then listner called
locationManager.requestLocationUpdates(provider, 2000, 10,
locationListener);
// send mcc,mnc,latitude,longitude,altitude,address,Link in message
String Url = "http://itouchmap.com/latlong.html";
sms.sendTextMessage(pn_no, null, "\nLocation:\n" + "MCC: " + mcc
+ "\nMNC: " + mnc + "\nLAC:" + LAC + latLongString
+ "\nAltitude:" + altitude + "feet"
+ "\nGo to Below site:\n" + Url, null, null);
sms.sendTextMessage(pn_no, null, "\nAddress:\n" + addressString,
null, null);
// stop service automatically
SMS_Service.this.stopSelf();
}
else {
Log.e("loation:", "Location not found");
SMS_Service.this.stopSelf();
}
}
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) {
// TODO Auto-generated method stub
addressString = "\nno address found";
// check location get or not from provider
if (location != null) {
// get latitude and longitude
double latitude = location.getLatitude();
double longitude = location.getLongitude();
latLongString = "\nLat:" + latitude + "\nLong:" + longitude;
Log.e("location", "" + latLongString);
// get altitude from method
altitude = ld.getElevationFromGoogleMaps(latitude, longitude);
Log.e("Altitude", "" + altitude);
// find address from latitude and longitude
Geocoder gc = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = gc.getFromLocation(latitude,
longitude, 1);
StringBuilder sb = new StringBuilder();
if (addresses.size() > 0) {
Address address = addresses.get(0);
for (int i = 0; i <= address.getMaxAddressLineIndex(); i++)
sb.append(address.getAddressLine(i)).append("\n");
}
addressString = sb.toString();
Log.e("Address", "" + addressString);
} catch (IOException e) {
}
} else {
latLongString = "\n No location found";
Log.e("location", "" + latLongString);
}
}
}
hey you can make the service and use this code to get altitude and latitude and decode this using class
Try This code
double longitude,latitude;
int lon,lat;
getcurrentloc.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(GpsLocationFinder.this, "Enable Your GPS", Toast.LENGTH_LONG).show();
}else{
LocationResult locationResult=new LocationResult() {
#Override
public void gotLocation(Location location) {
// TODO Auto-generated method stub
longitude=location.getLongitude();
latitude=location.getLatitude();
lon=(int)longitude;
lat=(int)latitude;
Toast.makeText(GpsLocationFinder.this, "Current Longitude"+longitude+" Current Latitude"+latitude,Toast.LENGTH_LONG).show();
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(GpsLocationFinder.this, locationResult);
}
}
});
And the MyLocation Class is Below
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
double longitude,latitude;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
//Log.e("GPS DISTANCE","GPS Enabled");
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
//don't start listeners if no provider is enabled
//try{
try{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}catch(Exception ex){
}
try{
network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch(Exception ex){
}
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
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);
}
}
i use the following code for getting the current latitude and longitude in services but it always return null. please help me.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println("provider "+provider);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Try this code for current location:
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10,
10, mlocListener);
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
VisualCV.this);
dlgAlert.setMessage("Gps Disabled ");
dlgAlert.setTitle("Message");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps enabled", Toast.LENGTH_SHORT ).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public void onLocationChanged(Location loc)
{
// TODO Auto-generated method stub
Latitud = loc.getLatitude();
longtitude = loc.getLongitude();
lang = String.format("%.4f", longtitude);//LONGITUDE
lati = String.format("%.4f", Latitud);//LATITUDE
}
}
Use this piece of code may be it may help you
import com.example.ConfigClass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
}
This is my code
First startGpsCallBack, then stop it and then call startGPSCallBackAgain method
Check it and let me know if this solves your problem
Try this.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
This is my last question about gps
Getting 0.0 for latitude and longitude while showing current location in map
Now here is the code I'm using to get the user's current location.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(crta, true);
Location loc = null;
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
}
LocationListener mlocListener = new MyLocationListener();
mlocListener.onLocationChanged(loc);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 10, mlocListener);
public class MyLocationListener implements LocationListener{
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location loc) {
if (null != loc) {
String Text = "Your current location is: \n" + "Latitude = \n"
+ loc.getLatitude() + "\nLongitude = \n" + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
GeoPoint myGeoPoint = new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
mpc.animateTo(myGeoPoint);
mpc.setZoom(10);
objMapView.invalidate();
}
}
#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) {
}
}
Now the problem I'm facing is, it is not showing me the current location when the gps is turned on. The loc object , loc = mlocManager.getLastKnownLocation(provider); always returns null. I got the value for provider as gps.
But if I turn of my gps connection, the same loc object will have relevant information and it works partiall correct. That means, it gives me the nearest location. I mean the full city location where I am sitting.
But if I on my gps connection, it does not give me even the city location also, does not enters if loop only inside location listener class. I am not getting what is going wrong here.
Any one can tell me how to solve it?
Update:
This is the value I get for loc object if my gps is off
Location[mProvider=network,mTime=1331718353322,mLatitude=12.9053401,mLongitude=74.8359128,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy=36.0,mExtras=Bundle[mParcelledData.dataSize=148]].
But if the gps is on, loca return null
CustomLocationManager.Java
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;
import android.os.Handler;
import android.os.Message;
public class CustomLocationManager {
private LocationManager mLocationManager;
private LocationValue locationValue;
private Location networkLocation = null;
private Location gpsLocation = null;
private Timer mTimer;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private static CustomLocationManager _instance;
private CustomLocationManager() {}
public static CustomLocationManager getCustomLocationManager() {
if (_instance == null) {
_instance = new CustomLocationManager();
}
return _instance;
}
public LocationManager getLocationManager(Context context) {
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return mLocationManager;
}
public boolean getCurrentLocation(Context context, LocationValue result) {
locationValue = result;
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
try {
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!isGpsEnabled && !isNetworkEnabled)
return false;
if (isGpsEnabled)
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
if (isNetworkEnabled)
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
mTimer = new Timer();
mTimer.schedule(new GetLastKnownLocation(), 20000);
return true;
}
LocationListener gpsLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(networkLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener networkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(gpsLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastKnownLocation extends TimerTask {
CurrentLocationHandler handler;
GetLastKnownLocation() {
handler = new CurrentLocationHandler();
}
#Override
public void run() {
mLocationManager.removeUpdates(gpsLocationListener);
mLocationManager.removeUpdates(networkLocationListener);
if (isGpsEnabled)
gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkEnabled)
networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
handler.sendEmptyMessage(0);
}
}
private class CurrentLocationHandler extends Handler {
#Override
public final void handleMessage(Message msg) {
if (gpsLocation != null && networkLocation != null) {
if (gpsLocation.getTime() > networkLocation.getTime())
locationValue.getCurrentLocation(gpsLocation);
else
locationValue.getCurrentLocation(networkLocation);
return;
}
if (gpsLocation != null) {
locationValue.getCurrentLocation(gpsLocation);
return;
}
if (networkLocation != null) {
locationValue.getCurrentLocation(networkLocation);
return;
}
locationValue.getCurrentLocation(null);
}
}
}
LocationValue.Java
import android.location.Location;
public abstract class LocationValue {
public abstract void getCurrentLocation(Location location);
}
YourActivity.Java
private void getCurrentLocation() {
CustomLocationManager.getCustomLocationManager().getCurrentLocation(this, locationValue);
}
public LocationValue locationValue = new LocationValue() {
#Override
public void getCurrentLocation(Location location) {
// You will get location here if the GPS is enabled
if(location != null) {
Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
}
}
};
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
First of all I'm not familiar with the Android location API, but did you try the GPS outside? Since GPS doesn't work inside buildings, it's pretty hard to retrieve the location of your mobile device using only your GPS. When indoors, typically your "GPS" position is determined using your WiFi acces point connection instead.