Android location loop - android

I'm using the following code to get the users location:
public class MainActivity extends ActionBarActivity {
//=========================================== On Create ========================================
#
Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//======================================= Location =========================================
LocationManager mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
}
public class MyLocationListener implements LocationListener {#
Override
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitude = " + loc.getLatitude() +
"Longitude = " + loc.getLongitude();
Toast.makeText(getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}#
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) {}
}
When I run the app, it goes into an endless loop of displaying me the location of the user. How can I make it show location only once with a click of a button?

Edited the code below to use either GPS or Network location.
Also use these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Here is a very simple case, a UI with just a Button and a TextView.
MainActivity.java:
public class MainActivity extends ActionBarActivity {
Button button;
TextView locText;
double lat;
double lon;
Location loc;
LocationManager mlocManager;
String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.buttonGo);
locText = (TextView)findViewById(R.id.textView);
mlocManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
//LocationListener mlocListener = new MyLocationListener();
//mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Criteria criteria = new Criteria();
//criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAccuracy(Criteria.ACCURACY_COARSE); //Try this instead
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
provider = mlocManager.getBestProvider(criteria, true);
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
lat = loc.getLatitude();
lon = loc.getLongitude();
}
locText.setText(lat + " " + lon);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
lat = loc.getLatitude();
lon = loc.getLongitude();
}
locText.setText(lat + " " + lon);
}
});
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<Button
android:id="#+id/buttonGo"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Refresh Location"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_below="#+id/buttonGo"
android:layout_marginTop="86dp" />
</RelativeLayout>

Related

Network location provider not giving location android

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();
}
}

Get latitude,longitude without touch

How to find user current location latitude,longitude without touch event?I searched in internet but i get latitude,longitude only touch event.
I've answered to similar question of yours here. Take a look at that. It doesn't need the google maps.
public class LocationSampleActivity extends Activity implements OnInitListener
{
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)this.findViewById(R.id.txtLocation);
tts = new TextToSpeech(this, this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener
{
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: "+
"\n Latitude: "+ location.getLatitude() +
"\n Longitude: " + location.getLongitude();
tv.append(str);
speak(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(LocationSampleActivity.this,"Error onProviderDisabled",Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(LocationSampleActivity.this,"onProviderEnabled",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(LocationSampleActivity.this,"onStatusChanged",Toast.LENGTH_LONG).show();
}
}
}
It will update your current location's latitude & longtitude into the TextView without touch simply. Please add the important permission into your manifest file.
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
use MyLocationOverlay for get current location.
MyLocationOverlay whereAmI = new MyLocationOverlay(this,mapview);
GeoPoint myLocationGeoPoint = whereAmI.getMyLocation();
float latitude = myLocationGeoPoint.getLatitudeE6() / 1E6;
float longitude = myLocationGeoPoint.getLongitudeE6() / 1E6;

LocationManager generating errorin code

this is my code in android and is showing error. I dont know what is wrong but i am certaqin it has to do something with LocationManager because until that line it works fine.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("Exception", "Something gone wrong !! ");
/*after this line it shows error */
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
All i want right now is to display value of longitude and latitude so that i can be sure code is good till here.
Declate this variable
Location loc;
Write this code in Oncreate() method
LocationManager mlocManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
Then Write
loc.getLatitude();
loc.getLongitude();
Now you can use the value of latitude and longitude... :-)
Use Below Code Snippet
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.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
{
#Override
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();
}
#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)
{
}
}
Check Below Line in Manifest file
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

Location is displaying as null when using LocationManager

I want to get current location's latitude and longitude. I used LocationManager for this, but it is displaying location as null and latitude and longitude as 0.0. I have used required permissions in manifest and GPS connection.
Code:
LocationdemoActivity.java:
public class LocationdemoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mlocListener);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(
getApplicationContext(),
"loc:" + MyLocationListener.location + "latitude "
+ MyLocationListener.latitude + "longitude "
+ MyLocationListener.longitude, 5000).show();
}
});
}
}
MyLocationListener.java:
public class MyLocationListener implements LocationListener {
public static double latitude;
public static double longitude;
public static Location location;
#Override
public void onLocationChanged(Location loc)
{
location = loc;
loc.getLatitude();
loc.getLongitude();
latitude = loc.getLatitude();
longitude = loc.getLongitude();
}
#Override
public void onProviderDisabled(String provider)
{
}
#Override
public void onProviderEnabled(String provider)
{
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
protected boolean isRouteDisplayed() {
return false;
}
}
Permissions in manifest:
<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"/>
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS"/>
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES"/>
What is the problem?
Try to do something like this
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener);
location = mlocManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Button buttonLocation = (Button) findViewById(R.id.buttonLocation);
buttonLocation.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(getApplicationContext(),
"loc:" + location + "latitude "
+ location.latitude + "longitude "
+ location.longitude, 5000).show();
}
});

How to get my current longitude and latitude from my Android device

I am using this code. but getting null in longitude and latitude.
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Take a look at this tutorial: A Deep Dive Into Location
Basically, if you want to get the approximate location using the last known location, you should iterate through all the possible providers with a loop like this:
List<String> matchingProviders = locationManager.getAllProviders();
for (String provider: matchingProviders) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
float accuracy = location.getAccuracy();
long time = location.getTime();
if ((time > minTime && accuracy < bestAccuracy)) {
bestResult = location;
bestAccuracy = accuracy;
bestTime = time;
}
else if (time < minTime &&
bestAccuracy == Float.MAX_VALUE && time > bestTime){
bestResult = location;
bestTime = time;
}
}
}
You can use the LocationManager. See the example:
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
And place it in Manisfest:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
did you added
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Permission to manifest file
Try This
public class LocationDemo extends Activity implements LocationListener {
private static final String TAG = "LocationDemo";
private static final String[] S = { "Out of Service",
"Temporarily Unavailable", "Available" };
private TextView output;
private LocationManager locationManager;
private String bestProvider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Get the output UI
output = (TextView) findViewById(R.id.output);
// Get the location manager
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// List all providers:
List<String> providers = locationManager.getAllProviders();
for (String provider : providers) {
printProvider(provider);
}
Criteria criteria = new Criteria();
bestProvider = locationManager.getBestProvider(criteria, false);
output.append("\n\nBEST Provider:\n");
printProvider(bestProvider);
output.append("\n\nLocations (starting with last known):");
Location location = locationManager.getLastKnownLocation(bestProvider);
printLocation(location);
}
/** Register for the updates when Activity is in foreground */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(bestProvider, 20000, 1, this);
}
/** Stop the updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
public void onLocationChanged(Location location) {
printLocation(location);
}
public void onProviderDisabled(String provider) {
// let okProvider be bestProvider
// re-register for updates
output.append("\n\nProvider Disabled: " + provider);
}
public void onProviderEnabled(String provider) {
// is provider better than bestProvider?
// is yes, bestProvider = provider
output.append("\n\nProvider Enabled: " + provider);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
output.append("\n\nProvider Status Changed: " + provider + ", Status="
+ S[status] + ", Extras=" + extras);
}
private void printProvider(String provider) {
LocationProvider info = locationManager.getProvider(provider);
output.append(info.toString() + "\n\n");
}
private void printLocation(Location location) {
if (location == null)
output.append("\nLocation[unknown]\n\n");
else
output.append("\n\n" + location.toString());
}
}
// main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:id="#+id/output" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</ScrollView>
</LinearLayout>
implementation 'com.google.android.gms:play-services-location:11.6.0'
public class LocationExample Eextends AppCompatActivity implements LocationListener {
double latitude, longitude;
LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getLocation()
}
void getLocation() {
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (isNetworkEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//GlobalToast.toastMessage(this, "please provide location permission.");
return;
}
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1, 400, this);
} else {
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (isGPSEnabled) {
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 400, this);
}
}
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("location", "change");
Log.d("latitude", String.valueOf(latitude));
Log.d("longitude", String.valueOf(longitude));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(getApplicationContext(), "Please Enable GPS and Internet", Toast.LENGTH_SHORT).show();
}
}

Categories

Resources