I have two question with my code
can not enter the onLocationChanged() function
mylocation is always null
I also add the permission and turn on my device GPS function
<uses-permission android:name ="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name ="android.permission.ACCESS_COARSE_LOCATION"/>
follows is my code please help me to get Latitude Lontitude thanks all.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Getaddress getaddress = new Getaddress();
getaddress.excute();
}
public class Getaddress implements LocationListener {
Geocoder geocoder;
private Location mylocation;
private double Latitude;
private double Lontitude;
private LocationManager locationManager;
public Getaddress() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, this);
mylocation = locationManager.getLastKnownLocation(provider);
Boolean isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.w("isGPSEnabled",isGPSEnabled.toString());
}
public void excute()
{
Latitude = mylocation.getLatitude();
Lontitude = mylocation.getLongitude();
Toast.makeText(SecondActivity.this, "Latitude"+Double.toString(Latitude),Toast.LENGTH_LONG).show();
}
#Override
public void onLocationChanged(Location location)
{
mylocation = location;
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Xml File :
<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" >
<TextView
android:id="#+id/tv_location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="#string/str_tv_location"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_longitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_location"
android:layout_centerHorizontal="true" />
<TextView
android:id="#+id/tv_latitude"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_longitude"
android:layout_centerHorizontal="true"/>
</RelativeLayout>
Java file:
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.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements LocationListener{
LocationManager locationManager ;
String provider;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting LocationManager object
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if(provider!=null && !provider.equals("")){
// Get the location from the given provider
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if(location!=null)
onLocationChanged(location);
else
Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
public void onLocationChanged(Location location) {
// Getting reference to TextView tv_longitude
TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude);
// Getting reference to TextView tv_latitude
TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude);
// Setting Current Longitude
tvLongitude.setText("Longitude:" + location.getLongitude());
// Setting Current Latitude
tvLatitude.setText("Latitude:" + location.getLatitude() );
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
Permission :-
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
At first: you need GPS available space.
Secondly: your location is always null, because your space for GRP LOCATION not available. You need to check if GPS working or not
onLocationChanged method work every time when your location changed.
public class GPSTracker implements LocationListener {
public GPSTracker(Context con){
LocationManager lm = (LocationManager) con.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
// do something here...
//location.getLatitude();
//location.getLongitude();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Related
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.widget.TextView;
import android.util.Log;
public class MainActivity extends Activity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
protected Context context;
TextView txtLat;
String lat;
String provider;
protected String latitude,longitude;
protected boolean gps_enabled,network_enabled;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 0; // 1 minute
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
boolean isGPSEnabled = false;
txtLat = (TextView) findViewById(R.id.textview1);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,enter code here
0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
txtLat = (TextView) findViewById(R.id.textview1);
txtLat.setText("Latitude:" + location.getLatitude() + ", Longitude:" + location.getLongitude());
}
#Override
public void onProviderDisabled(String provider) {
Log.d("Latitude","disable");
}
#Override
public void onProviderEnabled(String provider) {
Log.d("Latitude","enable");
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d("Latitude","status");
}
}
/*************************** Andriod Manifest ****************************** Has this tag also
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Attached is my code. It is returning isGpsEnabled as true, but OnLocationChanged event is not fired, Please suggest. I need it very important. If I use the same code using "Network provider" it is working and reurning current location latitude & longitude.
I'm not having any luck receiving any data from the GPS using the code below, and i'm not sure what I'm doing wrong, it seems like my code matches everything i see online. i'd like to eventually add this to a background service to log gps coordinates even when the activity isn't visible or if other apps are open and if the speed is greater than a certain defined amount, but at this point I can't even get any of the data to show up. i'm relatively new to android but i can't figure out what am i doing wrong?
public class MainActivity extends Activity {
TextView textView;
MyLocationListener myLocationListener;
LocationManager lm;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView = (TextView)findViewById(R.id.message);
addLocationListener();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void addLocationListener()
{
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
final String PROVIDER = lm.getBestProvider(c, true);
this.myLocationListener = new MyLocationListener();
this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0.0F, this.myLocationListener);
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0.0F, myLocationListener);
Log.d("LOC_SERVICE", "Service RUNNING!");
}
public void updateLocation(Location location)
{
double latitude, longitude;
latitude = location.getLatitude();
longitude = location.getLongitude();
int mph = convertSpeed(location.getSpeed());
Log.d("LOC_SERVICE", "mph: "+mph);
this.textView.setText(this.textView.getText()+"\n"+"lat: "+latitude+" lng: "+longitude+" mph: "+mph);
}
private int convertSpeed(float speed) {
int mph =(int)(2.236936D * speed);
return mph;
}
class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
Log.d("LOC_SERVICE", "Listener RUNNING!");
updateLocation(location);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
}
You need to use permission first:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Next you inside onCreate() method use below code to get access to GPS.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 1, this);
}
Now if GPS is not enabled then you need to refer below code. For detailed explanation, you can refer how to get[DEAD LINK] [current location in android]1 tutorial.
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
Here we have used intents to redirect user to location settings page so that he can enable the GPS under location settings.
you can achieve this easily. you have to write code in main activity. and Main activity implements Locationlistner interface. and overload its four methods. here i'am retrieving my Longitude and Latitide co-ordinates in a textview when application started. and you have to give permission for access location in your manifest file.
as under my code.
package com.nisarg.gpsdemo;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements LocationListener {
private LocationManager locationManager;
private TextView textview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.textView);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
Location location = locationManager.getLastKnownLocation(locationManager.NETWORK_PROVIDER);
onLocationChanged(location);
}
#Override
public void onLocationChanged(Location location) {
double longitude=location.getLongitude();
double latitude=location.getLatitude();
textview.setText("Longitude: "+longitude+" Latitide: "+latitude);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
and you have to give permission like this in manifest file.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
And last warning.
you have to give permission to your application and start mobile data and GPS before you open application. either it will be crashed.
that's it.
hope it will help you. :)
I am trying to get a location (latitude, longitude) on my Android smartphone (HTC Desire HD), using Wifi-network and GPS.
This is the code I use, only I keep getting "Location not available"
Iam working with Eclipse IDE.
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import com.example.shortsproject.R;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class LocationGetter extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.location);
latituteField = (TextView) findViewById(R.id.locationtext);
longitudeField = (TextView) findViewById(R.id.locationtext2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location 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) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
}
Can someone help me with this?
What I am doing is trying to get a basic GPS working and can't figure out the problem (there is no errors coming up). When i run it on the emulator it crashes. I am using android 2.2
package Weather.app;
import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.Geocoder;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class WeatherAppActivity extends Activity{
/** Called when the activity is first created. */
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
protected LocationManager locationManager;
protected LocationListener MyLocationListener;
protected Button findButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findButton = (Button) findViewById(R.id.findButton);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
(LocationListener) this
);
findButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCurrentLocation();
}
});
}
protected void showCurrentLocation() {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String message = String.format(
"Current Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message,
Toast.LENGTH_LONG).show();
}
final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude()
);
Toast.makeText(WeatherAppActivity.this, message, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String s, int i, Bundle b) {
Toast.makeText(WeatherAppActivity.this, "Provider status changed",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider disabled by the user. GPS turned off",
Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String s) {
Toast.makeText(WeatherAppActivity.this,
"Provider enabled by the user. GPS turned on",
Toast.LENGTH_LONG).show();
}
}
}
}
This is also in my manifest:
<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.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.CONTROL_LOCATION_UPDATES" />
I have updated this code as I have made a few changes
Here is one example of working basic GPS activity:
public class UseGpsActivity extends Activity {
/** Called when the activity is first created. */
#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);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
double lati = loc.getLatitude();
double longi = loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + lati + "Longitud = " + longi;
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),"Gps Enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}
Unless some code is missing in your post MyLocationListener (you should not user upper case identifiers for instance fields!) is not initialized when passing the reference (i.e. null) to requestLocationUpdates().
You don't need to create another LocationListener, the statement
WeatherAppActivity extends Activity implements LocationListener
and the overriden methods
#Override
public void onLocationChanged(Location location)
etc means you have one in your main class already, so get rid of the inner class MyLocationListener completely.
Put your Toast code etc inside the overriden listener methods in the main class.
Then in onCreate() have :
locationManager.requestLocationUpdates(
locationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
this
);
I have a tutorial on Android location services on my blog. I'm not sure of your specific error but you can look at the code to see if it helps you!
http://www.scotthelme.co.uk/blog/android-location-services/
I'm using this script by Fedor but I want a little difference: When both GPS and Network Provider is unavailable, I want to app to return null or "unknown" string. I modified the script, but when I run, it force closes, the logcat says:
I have the following codes:
MyLocation.java
package com.example.GetALocation2;
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(), 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);
}
}
GetALocation2.java
package com.example.GetALocation2;
import com.example.GetALocation2.MyLocation.LocationResult;
import android.app.Activity;
import android.location.Location;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class GetALocation2 extends Activity {
Double latitude;
TextView tv;
MyLocation myLocation = new MyLocation();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "This is the start!", Toast.LENGTH_SHORT).show();
locationClick();
}
private void locationClick() {
myLocation.getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
//Got the location!
if( location == null ){
Toast.makeText(getBaseContext(), "Location is unknown.", Toast.LENGTH_SHORT).show();
}else{
GetALocation2.this.latitude = location.getLatitude();
Toast.makeText(getBaseContext(), "I got the location! >>> " + location.getLatitude(), Toast.LENGTH_SHORT).show();
}
};
};
}
I'm kinda new to java and android, many thanks for any help! :)
Hope this helps:
private LocationManager lm;
private LocationListener ll;
public static String latitude;
public static String longitude;
double lat,lon;
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if(lm.isProviderEnabled(LocationManager.GPS_PROVIDER)){
// Toast.makeText(this,"GPS PROVIDER", Toast.LENGTH_LONG).show();
ll = new GpsListener();
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0,ll);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0, ll);
}else if(lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
// Toast.makeText(this,"NETWORK PROVIDER.", Toast.LENGTH_LONG).show();
ll = new GpsListener();
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,0, ll);
}else{
Toast.makeText(this,"GPS is disabled.", Toast.LENGTH_LONG).show();
prog.dismiss();
}
Add the above code in your OnCreate method
and out of the onCreate method create a following class
private class GpsListener implements LocationListener
{
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
float acc=-1;
if(location!=null) {
Toast.makeText(HomeScreen.hs,"Location Found", Toast.LENGTH_LONG).show();
System.out.println("IN IF PART");
if(location.hasAccuracy())
acc = location.getAccuracy();
lat = location.getLatitude();
lon = location.getLongitude();
isLocFound=true;
latitude = Double.toString(lat);
longitude = Double.toString(lon);
System.out.println("1)"+acc+" 2) "+latitude+" 3) "+longitude);
lm.removeUpdates(ll);
lm = null;
stopSelf();
//stopForeground(true);
}else{
Toast.makeText(HomeScreen.hs,"No Location Found", Toast.LENGTH_LONG).show();
System.out.println("IN ELSE PART..");
}
prog.dismiss();
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}//end of Class
Hope this helpss