Get location not working on android - android

With this code I'm trying to get get the location this code only works the first time I execute the emulator the Ihave to close the emulator in order to work again ,and it doesn't launch any error
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
myContext = this;
position =(TextView)findViewById(R.id.position);
locationManager=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(android.location.Location location) {
double latitude=location.getLatitude();
double longitude=location.getLongitude();
position.setText("lat:"+latitude+" lon:"+longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
101);
}
else{
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
try {
switch (requestCode) {
case 101: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
}
return;
}
}
}
catch(SecurityException err_permission) {
}
}
}
and this permision on manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
But the position is not shown on the textview, I think I don't missed anything,Do I?Maybe coarse_location permission ?I don'k know what is wrong on this code it has the locationmanager and the listener, and aks form permission...

Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null){
}
else{
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
}
If you have the location you are not starting periodic updates, you may be looking for this:
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0, locationListener);
if(location != null){
//Do things with the first location
}
So you start with something and keep updating with the listener

If there is a last known location from locationManager.getLastKnownLocation then you don't request location updates.

Related

Can't get location by Network provider in Oreo

I want to get location from GPS provider and network provider. I wrote below code and works correct in android below 6 and i checked in android 4.2 and everything is correct but when i checked in android 8 till GPS is on, everything is worked and i get location by network or GPS. but when GPS is off, i can't get location by Network provider. What is my problem and How can i solved this? Do on API 23+, needs enable GPS for get location? Do i need enable an option in settings of my device?
public void createLocation(){
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
gpsLocListener = new MyLocationListener();
networkLocListener = new MyLocationListener();
}
...
public static void checkLocation() {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) && ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, networkLocListener);
}
if (!FIND_LOC_ByY_GPS) {
if (Build.VERSION.SDK_INT >= 23) {
if ((ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED)&& ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
} else {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocListener); }
//locationManager.requestLocationUpdates(locationManager.PASSIVE_PROVIDER,0,0,passiveLocListener);
}
}
public static class MyLocationListener implements LocationListener {
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location location) {
if (location != null && !callLocationUpdate) {
//Speed
//if (calculateSpeedUser(location) < 13.8889) {
try {
removeLocationUpdate();
callLocationUpdate = true;
if (DEBUG_BASEACTIVITY)
Log.e("GPS Location Changed!", "onLocationChanged/BaseActivity");
} catch (SecurityException e) {
Log.e("PERMISSION_EXCEPTION", "PERMISSION_NOT_GRANTED");
}
//}
get_location_by_LocationUpdate_method = true;
doLocationUpdate(location, true);
getByLocationUpdate = true;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}

Get current location latitude and longitude without using GPS

hi friends i am in trouble i want to find my current location lat long without using GPS ,can anyone help me..
Below is my code but its not working
public Location getLocation() {
Location location = null;
final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
try {
LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
//updating when location is changed
if (location != null) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Log.i("latitudelongitude", longitude + "," + latitude);
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isNetworkEnabled && !isGPSEnabled) {
//call getLocation again in onResume method in this case
// startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
} else {
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
Log.d("GPS", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
//Request for the ACCESS FINE LOCATION
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
//call the getLocation funtion again on permission granted callback
}enter code here
return location;
}

finding location from requestLocationUpdates() from GPS not working

I am creating a map application, which gets location from GPS, i'm finding location from requestLocationUpdates(), but i'm not getting any response from GPS provider, however when i'am using network provider i'am getting location, can anyone help where i'm wrong,
Also i'am new to android app development, so i'll appreciate any tips to optimize my code(make more efficient with less mess),
Here's my code :
public void trackLocation(){
if (ContextCompat.checkSelfPermission(activity.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
boolean flag;
Boolean dlg;
flag = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (flag) {
Log.v("function", "onClick");
myLocationListener = new MyLocationListener();
dlg = true;
} else {
dlg = gpsDialog();
progressBar.setVisibility(View.GONE);
}
Log.d("maps", "Requesting location updates");
if(dlg) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, myLocationListener);
}
}
}
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Log.d("maps", "on location changed : "+location.getLatitude() + "---"+ location.getLongitude());
locationManager.removeUpdates(myLocationListener);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.d("maps" , "Status Changed");
}
#Override
public void onProviderEnabled(String s) {
Log.d("maps" , "Provider Enabled");
}
#Override
public void onProviderDisabled(String s) {
Log.d("maps" , "Provider Disabled");
}
}
public Boolean gpsDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage("Do you want to start GPS?")
.setCancelable(false)
.setTitle("GPS DISABLED")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// finish the current activity
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
activity.startActivity(myIntent);
dialog.cancel();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// cancel the dialog box
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
progressBar.setVisibility(View.GONE);
return false;
}
Google maps uses user's lastKnownLocation for location, If the lastknownLocation is unknown it takes time to fetch location through different provider say GPS or Network, whichever is easy. I would suggest to use lastKnownLocation as base location and update it with LocationListener. It is most optimized way of processing location.
if (ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ActivityCompat.checkSelfPermission
(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION
}, 1);
}
else {
// enable location buttons
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// fetch last location if any from provider - GPS.
final LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
final Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//if last known location is not available
if (loc == null) {
final LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
// getting location of user
final double latitude = location.getLatitude();
final double longitude = location.getLongitude();
//do something with Lat and Lng
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
//when user enables the GPS setting, this method is triggered.
}
#Override
public void onProviderDisabled(String provider) {
//when no provider is available in this case GPS provider, trigger your gpsDialog here.
}
};
//update location every 10sec in 500m radius with both provider GPS and Network.
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10*1000, 500, locationListener);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 500, locationListener);
}
else {
//do something with last known location.
// getting location of user
final double latitude = loc.getLatitude();
final double longitude = loc.getLongitude();
}
}
Permission handling:
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case 1:
if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
//do something
}
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Your code is correct. GPS usually doesn't give you any info within the building, if you try to test the app outside, you will get the results.
firstly check gps_enabled return true or not.
LocationManager lm = (LocationManager) mCtx
.getSystemService(Context.LOCATION_SERVICE);
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
By this code you get accurate lat , long
Location net_loc = null, gps_loc = null, finalLoc = null;
if (gps_enabled)
gps_loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (gps_loc != null && net_loc != null) {
if (gps_loc.getAccuracy() >= net_loc.getAccuracy())
finalLoc = gps_loc;
else
finalLoc = net_loc;
// I used this just to get an idea (if both avail, its upto you which you want to take as I taken location with more accuracy)
} else {
if (gps_loc != null) {
finalLoc = net_loc;
} else if (net_loc != null) {
finalLoc = gps_loc;
}
}

Android app missing status bar icon when accessing location services

Ok this is a weird one but I maybe missing something that is obvious. I am currently accessing the user location using this function:
public String[] getGeoCoords() {
String[] geoCoords = new String[2];
String mprovider = locationManager.getBestProvider(criteria, false);
if (mprovider != null && !mprovider.equals("")) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return geoCoords;
}
Location loc = locationManager.getLastKnownLocation(mprovider);
if(loc== null)
loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (loc == null)
loc = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
if (loc == null)
loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
geoCoords[0] = String.valueOf(loc.getLatitude());
geoCoords[1] = String.valueOf(loc.getLongitude());
}
return geoCoords;
}
This returns the location as expected but the icon that you normally get when accessing the user location does not appear in the status bar.
In my Manifest I have
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Any ideas?
you are accessing getLastKnownLocation() which returns last available location directly else it returns null.
The icon your are talking about comes when you request for location update like this..
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
so while it searches for satellites, it shows that gps icon and when it found one onLocationChanged(Location location) will be called with captured location.

getLastKnownLocation always returns null - API 23

I'm trying to make an application that works with the user's location.
First, I did a little test app to return the user's location at getLastKnownLocation assigning permission control requested by API 23.
The control of location is made by the condition
if (location != null){
Log.i("LogX","Got Location!");
} else{ Log.i("LogX","It has location");}
The problem is that at all times, returns "It has location".
I think that should be something related to the use of getLastKnownLocation.
My MainActivity
public class MainActivity extends AppCompatActivity implements LocationListener{
LocationManager locationManager;
String provider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
permissaoMapa();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
provider = locationManager.getBestProvider(new Criteria(), false);
Location location = locationManager.getLastKnownLocation(provider);
if (location != null){
Log.i("LogX","Got Location!");
} else{ Log.i("LogX","It has location");}
}
private void permissaoMapa(){
if(ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.ACCESS_COARSE_LOCATION)){
}else{
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},0);
}
}else {
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
for (int result : grantResults) {
if (result == PackageManager.PERMISSION_DENIED) {
return;
} else {
if (grantResults.length ==1) {
}
}
}
}
#Override
public void onLocationChanged(Location location) {
Double lat = location.getLatitude();
Double lon = location.getLatitude();
Log.i("LogX",lat.toString());
Log.i("LogX", lon.toString());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
}
For the getLastKnownLocation work, I did the following steps:
I open the terminal and typed the command "telnet localhost 5554" where 5554 refers to the AVD port
Open the Maps application that comes installed on AVD
Input the command line "geo fix 12 45" in the terminal . In this example you can type any latitude and longitude information.
There, after it managed to get the location.

Categories

Resources