I use below code to get current location of user. This code work in emulator but when I use this application in mobile it unable to give current latitude and longitude.
I uses <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> this code in android manifest file.
Please give me solution... my code is below
public class MenuPage extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.menupage);
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
/* Start of Class MyLocationListener for get current location of user */
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location crurrentLocation)
{
Log.v("WHERE ","onLocationChanged()");
crurrentLocation.getLatitude(); // get current latitude
crurrentLocation.getLongitude(); // get current longitude
longitude=crurrentLocation.getLongitude();
latitude= crurrentLocation.getLatitude();
Log.v("WHERE ","onLocationChanged() Latitude="+latitude);
Log.v("WHERE ","onLocationChanged() Longitude="+longitude);
Toast.makeText(getApplicationContext(),"Latitud="+crurrentLocation.getLatitude(),Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),"Longitud="+crurrentLocation.getLongitude(),Toast.LENGTH_SHORT).show();
send_current_location = new Send_Current_location_ToServer();
// Send current location to server
String server_message = send_current_location.sendData(userid,latitude,longitude);
// String text ="My current location is: " + "Latitud = " + crurrentLocation.getLatitude() + "Longitud = " + crurrentLocation.getLongitude();
// Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Log.v("WHERE ","onProviderDisabled()");
Toast.makeText( getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Log.v("WHERE ","onProviderEnabled()");
Toast.makeText( getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
Log.v("WHERE ","onStatusChanged()");
}
}/* End of Class MyLocationListener */
}
There is a bug in the 2.3 emulator concerning the location services. Try changing to 2.1 to test your code.
For more info about location services, use this.
See here for the status of the bug.
Related
I am new in android developing, and so intrested in getting location of users!!!!!
You may know that we can access users location by two types:
GPS (ACCESS_FINE_LOCATON)
Network based (ACCESS_COARSE_LOCATION)
My Question is:
I Want to get the location(latittude & longitude) of user by GPS. But, if the user has turned GPS Off/GPS isn't supported, then i want to get user's location by Network, or, Network-based location
.
Hope you understood my question....
Any help is accepted
Try the following code:
LocationManager mlocManager;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
//if condition to check if GPS is available
if (mlocManager .isProviderEnabled(LocationManager.GPS_PROVIDER)) { mlocManager.requestSingleUpdate(LocationManager.GPS_PROVIDER,
mlocListener, null);
}
else if (mlocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
mlocManager.requestSingleUpdate(
LocationManager.NETWORK_PROVIDER, mlocListener, null);
}
//this is the class to get the location.
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
try {
//you may store these values where ever required.
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
} catch (Exception e) {
e.printStackTrace();
}
}
#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
}
}
When you use the FusedLocationProviderApi as used in the getting the last known location training and receiving location updates training, it will automatically fall back to network location if GPS is not available.
Hope get GPS code helps you.
if (Common.getIsGPSEnabled()) {
final LocationManager locationManager = (LocationManager) c.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener;
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
myLocation = locationManager.getLastKnownLocation(locationProvider);
Toast.makeText(c, "location changed, My location is removed to"
+ myLocation.getLatitude()+","+myLocation.getLongitude(), Toast.LENGTH_LONG).show();
Latitude = myLocation.getLatitude();
Longitude = myLocation.getLongitude();
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
locationManager.requestLocationUpdates(locationProvider, (long)0, (float)0, locationListener);
myLocation = locationManager.getLastKnownLocation(locationProvider);
if(myLocation != null)
{
///
}
}
I am developing a small android application in which I want to find out the user's current location by using the network provider. I tried this in following ways but it's not giving me any output :
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
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
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
I gave permissions in my manifest file like this
<uses-permission
android:name="android.permission.INTERNET" />
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
Is there any thing which I am missing ? Is this the correct way? Need help. Thank you...
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager gpslocationManager;
private LocationManager networklocationManager;
private LocationManager networklocationManager1;
private String provider;
private TextView gps_location;
private TextView network_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gps_location = (TextView) findViewById(R.id.gps_location);
network_location = (TextView) findViewById(R.id.network_location);
networkLocation();
}
public void networkLocation() {
networklocationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i("********************************",
"this is my network location " + location);
String Location_text = "NETWORK LOCATION latitude:"
+ location.getLatitude() + " longitude:"
+ location.getLatitude();
network_location.setText(Location_text);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
networklocationManager
.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,
networklocationListener);
}
}
Make sure you enable Location Services in Settings! That should be the problem. It might be disabled (and this setting will usually be found in Location and Security in Settings)
Let me know if it works!
Is your network provider enabled?
boolean network_enabled;
try {
network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch(Exception ex) {
ex.printStackTrace();
}
I hope this part of the code will help you extracted from vogella.
public class ShowLocationActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
// Get the location manager
locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the locatioin provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null) {
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
} else {
latituteField.setText("Location not available");
longitudeField.setText("Location 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());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
I have a problem with my simple android aplication that use GPS cords.
My class MyLocationListener implements LocationListener, and there is a static method call:
String strText ="My current location is: " + "Latitude = " + location.getLatitude() + " Longitude= " + location.getLongitude();
Toast.makeText(GpsModule.cont, strText, Toast.LENGTH_SHORT).show();
Problem is with displaying this string. It's showing up, and never ends. When I press back button for main menu and even when I close application it's showing up constantly. Any clue? How can I resolve this problem?
GpsModule Class:
public class GpsModule extends Activity {
public static Context cont;
//public static WebView position;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.gps);
cont = getApplicationContext();
//position = new WebView(cont);
//position = (WebView) findViewById(R.layout.gps);
//position.getSettings().setJavaScriptEnabled(true);
LocationManager locManager = (LocationManager) getSystemService(LOCATION_SERVICE);
LocationListener locListener = new MyLocationListener();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
}
MyLocationListener class:
#SuppressLint("ShowToast")
public class MyLocationListener implements LocationListener{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
location.getLatitude();
location.getLongitude();
String strText ="My current location is: " + "Latitude = " + location.getLatitude() + " Longitude= " + location.getLongitude();
Toast.makeText(GpsModule.cont, strText, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(GpsModule.cont, "GPS disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(GpsModule.cont, "GPS enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Please read the docs of the method LocationManager.requestLocationUpdates().
Especially the parameter:
minTime minimum time interval between location updates, in milliseconds.
Try value 10'000 for every 10 sec. In production you should consider value more than mins.
I think, you add your code in your location detection function and LocationListener is active. That means your Toast is called when GPS detect new location.
Looks like your location listener is active and repeatedly gets called. are you moving your device? LocationListener is called when the location changes.
Try this,
1 .
Toast.makeText(getBaseContext(), strText, Toast.LENGTH_SHORT).show();
2 .
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(locationListener);
}
3 .
#Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
Length, long, locationListener);
}
Length and long should be more than 0.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I get the current GPS location programmatically in Android?
Got a code below.. Will this get me my own location..?
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
latitude=loc.getLatitude();
longitude=loc.getLongitude();
}
public void onProviderDisabled(String provider)
{
//print "Currently GPS is Disabled";
}
public void onProviderEnabled(String provider)
{
//print "GPS got Enabled";
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
I know this has been asked several times.. Please help me with the code...
You may use this code to start listing for GPS updates and do something with the data you receive. It also prints messages in the log file for easy debugging. Please, note, this function does not return any results, it only starts listening to GPS. Results will be provided some time later in // do something here with the new location data part, when you may save them somewhere.
private void getGpsData() {
locationManager = (LocationManager) owner.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.i(TAG, "location change:" + location.toString());
String longitude = "Londitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
if( location.hasAccuracy() ) { // good enough?
// do something here with the new location data
....
//
Log.i(TAG, "GPS listener done");
locationManager.removeUpdates(this); // don't forget this to save battery
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, provider + " status:" + status);
}
public void onProviderEnabled(String provider) {
Log.i(TAG, provider + " enabled");
}
public void onProviderDisabled(String provider) {
Log.i(TAG, provider + " disabled");
}
};
Log.i(TAG,"GPS listener started");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener );
}
I am new to android, can anyone help me for my question....
How to get a current position and tracking in map using GPS without giving any location in a program?????
You want the easy way out ! Use MyLocationOverlay object. you can get the current location by calling the method getLastFix(); . To enable tracking use enableMyLocation(). To add this object to the map you need to add it to your map overlays.
MyLocationOverlay currLoc=new MyLocationOverlay(context,mapKey);
mapView.getAllOverlays.add(currLoc);
currLoc.enableMyLocation();
Location myLastLocation=currLoc.getLastFix();
currLoc.enableCompass();
Do make sure, in onPause() you do this :
currLoc.disableMyLocation(); //to save battery.
you can resume updates in onResume() by calling currLoc.enableMyLocation();
This is the easiest way I could find! and it is quite accurate too
Try ;
String m_BestProvider;
LocationManager m_LocationManager;
LocationListener m_LocationListener = null;
Location m_Location = null;
m_LocationManager = (LocationManager) m_Context.getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
m_BestProvider = m_LocationManager.getBestProvider(c, false);
// Define a listener that responds to location updates
m_LocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
m_LocationManager.requestLocationUpdates(m_BestProvider, 0, 0, m_LocationListener);
m_Location = m_LocationManager.getLastKnownLocation(m_BestProvider);
Systme.out.println(m_Location.getLatitude() "," +m_Location.getLongitude());
Add in AndriodManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
public class GPSLocationBased extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locationbased);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new Mylocationlistener();
// ---Get the status of GPS---
boolean isGPS = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
// If GPS is not enable then it will be on
if(!isGPS)
{
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
sendBroadcast(intent);
}
//<--registers the current activity to be notified periodically by the named provider. Periodically,
//the supplied LocationListener will be called with the current Location or with status updates.-->
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
/**
*Mylocationlistener class will give the current GPS location
*with the help of Location Listener interface
*/
private class Mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// ---Get current location latitude, longitude, altitude & speed ---
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
float speed = location.getSpeed();
double altitude = location.getAltitude();
Toast.makeText(GPSLocationBased.this,"Latitude = "+
location.getLatitude() + "" +"Longitude = "+ location.getLongitude()+"Altitude = "+altitude+"Speed = "+speed,
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
Through this code u will get ur lat and long.
and u may use it on ur gmap.
this code also start gps functionality problematically. Hope this will help u.. All the best :)