Google map with acceleration detection not working in android studio - android

I am making an app with Android Studio where the google maps shows the user's location, and i want to add an acceleration detector so when the acceleration of the user is very large, an alert dialog pops up.
The map with the user's location is working, but when I try to add the acceleration sensor, the app crashes (no error warning). The code is the following:
public abstract class Mapa extends FragmentActivity implements OnMapReadyCallback, SensorEventListener {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
private SensorManager sensorManager;
Sensor accelerometer;
private SensorManager sensorManager2;
Sensor giroscopio;
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mapa);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION);
sensorManager.registerListener(Mapa.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float acX;
acX = sensorEvent.values[0];
if (acX >= 10 ){
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("Warning!");
AlertDialog mensajealerta = builder1.create();
mensajealerta.show();
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng posicion = new LatLng(location.getLatitude(), location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
if (Build.VERSION.SDK_INT < 23) {
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else { locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location ultimaPosicion = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng posicion = new LatLng(ultimaPosicion.getLatitude(), ultimaPosicion.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(posicion).title("Estás aquí!"));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(posicion, 20));
}
}
}
}
I don't understand where the error is, could you help me please?

I finally figured it on my own, so I'll post the answer in case anyone else may need it.
Apparently it does not work when you put the Google maps and the accelerometer in the same activity, so I had to separate them. Ir order to do so, I used a Service for detecting the acceleration.
I managed to get my Service going by looking at this:
Android sensors not working in a service
Once this is done, I send my accelerometer info to my maps activity with a LocalBroadcastManager:
How to use LocalBroadcastManager?
By following the instructions given in these 2 questions I managed to make it work.

Related

I want my MainActivity.java to have a button which when tapped should execute the code written in MapsActivity.java

I created a MapsActivity and corresponding activity_maps.xml.My activity_main.xml there will be a button which when tapped should show the current location pointed by a marker.
Code works fine when making the MapsActivity as Launcher Activity in AndroidManifest.xml but want my MainActivity to be the Launcher Activity.
how I can make my MainActivity as Launcher Activity.
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap) {
Toast.makeText(this, "inside onMapReady()", Toast.LENGTH_SHORT).show();//doesn't appear
Log.i("hurray:","inside onMapReady()");//doesn't appear
mMap = googleMap;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(#NonNull Location location) {
if(location != null){
Toast.makeText(MapsActivity.this, "Location is not null", Toast.LENGTH_SHORT).show();//doesn't appear
LatLng userLatLngLocation = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(userLatLngLocation);
markerOptions.title("Current position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
mMap.addMarker(markerOptions);
mMap.moveCamera(CameraUpdateFactory.newLatLng(userLatLngLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(10));
Toast.makeText(getApplicationContext(), location.toString(), Toast.LENGTH_SHORT).show();//does appears sometimes
}
else{
Toast.makeText(getApplicationContext(), "location is null !", Toast.LENGTH_SHORT).show();
}
}
public void requestLocationPermission() {
//if permission not granted ask for it
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
//else if location permission is already granted get location updates
else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//every 0secs & 0meters
}
}
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, int grantResults[]) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
Button getPopLocationButton;//button to show the Maps
MapsActivity mapsActivity;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_screen);
mapsActivity = new MapsActivity();
getPopLocationButton = findViewById(R.id.buttonPopLocation);
getPopLocationButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setContentView(R.layout.activity_maps);
}
});
}
}
Okay I got this working,
public void onClick(View view){
setContentView(R.layout.map);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(MainActivity.this);}

how i can access current user location in fragments using API28?

i want to access current location in fragments , but i am using API 28 and android version 3.2.1. i try everything from internet follow tutorials but i cant access my current location , there is no error in my code but i don't know why i cant access it. when i run my program i just see google default map, no marker etc.
i want to access my location through network provider as well as gps provider if network provider is not available.
i also add 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_NETWORK_STATE" />
for a permission access i am using library from github and for lacation and map
implementation 'pub.devrel:easypermissions:2.0.0'
implementation 'com.google.android.gms:play-services-maps:16.0.0'
implementation 'com.google.android.gms:play-services-location:16.0.0'
please check my code and guide me how i can access current location my code is in below in my code there is also step counter code but ignore that one.
here is my code
public class HomeActivity extends Fragment implements SensorEventListener, OnMapReadyCallback {
SensorManager sensorManager;
TextView set_steps;
TextView set_calories;
TextView set_distance;
boolean running = false;
private static int steps;
private static int calories;
private static double distance;
private GoogleMap mMap;
LocationManager locationManager;
public static final int Request_User_Location_Code = 99;
GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location lastLocation;
private Marker currentUserLocationMarker;
private final int REQUEST_LOCATION_PERMISSION = 1;
Provider provider;
View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.activity_home, container, false);
requestLocationPermission();
stepsCounter();
locationTracker();
return view;
}
void stepsCounter() {
set_steps = (TextView) view.findViewById(R.id.set_steps);
set_calories = (TextView) view.findViewById(R.id.set_calories);
set_distance = (TextView) view.findViewById(R.id.set_distance);
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener((SensorEventListener) getActivity(), countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(getActivity(), "Sensor not Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause() {
super.onPause();
running = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (running) {
steps = (int) event.values[0];
set_steps.setText(steps + "");
caloriesCounter();
distanceCover();
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
void caloriesCounter() {
calories = steps / 20;
set_calories.setText(calories + "");
}
void distanceCover() {
distance = (double) steps * 0.76;
String distanceText = Double.toString(distance);
set_distance.setText(distanceText);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
}
void locationTracker() {
SupportMapFragment mapFragment = (SupportMapFragment) getChildFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
if ((ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) && (ActivityCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
}
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng= new LatLng(latitude,longitude);
Geocoder geocoder=new Geocoder(getActivity().getApplicationContext());
try {
List<Address> addressList = geocoder.getFromLocation(latitude,longitude,1);
String str = addressList.get(0).getLocality()+",";
str+= addressList.get(0).getCountryName();
mMap.addMarker(new MarkerOptions().position(latLng).title(str));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
});
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// Forward results to EasyPermissions
EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
}
#AfterPermissionGranted(REQUEST_LOCATION_PERMISSION)
public void requestLocationPermission() {
String[] perms = {Manifest.permission.ACCESS_FINE_LOCATION};
if(EasyPermissions.hasPermissions(getActivity(), perms)) {
// Toast.makeText(getActivity(), "Permission already granted", Toast.LENGTH_SHORT).show();
}
else {
EasyPermissions.requestPermissions(this, "Please grant the location permission", REQUEST_LOCATION_PERMISSION, perms);
}
}
}
but remember i am using ApI 28

Not showing marker on map

I want get the current location of user on map
when I run the app ,app is successfully launched it takes the permission from user to take location of user through GPS but marker is not showing on map.
when i run the this app on emulator it shows some where else location and when i run this app on mobile it does not show location(marker)
her is the code .
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
LocationManager locationManager;
LocationListener locationListener;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode ==1) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.i("Location::::::", location.toString());
LatLng person = new LatLng(location.getLatitude(),location.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(person).title("person").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(person, 15));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if(Build.VERSION.SDK_INT < 23){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0 ,locationListener);
}
else {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
Location lastLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
LatLng loc = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
mMap.clear();
mMap.addMarker(new MarkerOptions().position(loc).title("person").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(loc, 15));
}
}
}
}
when i run the this app on emulator it shows some where else location
It's not showing your current location because when using the emulator, it's location is set in the settings, it doesn't determine your actual location, so basically it's set manually.
when i run this app on mobile it does not show location(marker)
Regarding that, you can try calling addMarker in onMapReady directly first. And moving your onLocationChanged callback outside of the onMapReady.

Android - Google Maps - LocationListener - adding marker onLocationChanged makes app crash

I want a marker to show my current location. All permissions needed are added. When I comment out mMap.addMarker and mMap.moveCamera the app is working and Googlemaps is shown. If I let one of those two in my code the app crashes before the map even opens.
I've tried with removing the marker if it isn't null but this doesn't solve the problem.
Do you guys have any idea how I can get the app working?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap mMap;
private List<LatLng> fountain = null;
private LocationManager locationManager;
private double posLat;
private double posLng;
private LatLng position;
private Marker mPosition;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
startGPS();
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
// Add a marker in Sydney and move the camera
LatLng sydney = new LatLng(48.16786112327462, 16.383984438313828);
mPosition = mMap.addMarker(new MarkerOptions().position(sydney).title("Your Position").icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}
//--------------------------------------------GPS Listener---------------------------------------
public void startGPS() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 5);
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this);
onLocationChanged(locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER));
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 5: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
} else {
getDialog2("Keine Erlaubnis für GPS").show();
}
}
}
}
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
//----------------------------Helper Methods-----------------------------------------------
public Dialog getDialog2(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
return builder.create();
}
public Dialog getDialog(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string);
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
}
Okay, I already solved the problem. So I post the solution here.
I have implemented on the MapsActivity the LocationListener interface and for some reason it doesn't work this way. I can retrieve the geocoordinates but as soon as I want to move the camera or add a marker it the app crashes as it gets opened.
I don't know why, but instead of:
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, this)
I undo the implementation of the LocationListener and just create a new one at the position of ,,this":
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 5, new LocationListener() {
#Override
public void onLocationChanged(Location location) {
posLat = location.getLatitude();
posLng = location.getLongitude();
position = new LatLng(posLat, posLng);
if (mPosition != null) {
mPosition.remove();
}
mPosition = mMap.addMarker(new MarkerOptions().position(position).title("Your position").
icon(BitmapDescriptorFactory.fromResource(R.drawable.location)));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 11));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
);
and this way it works without problem.

Location-code is not working anymore

I am using this code in android 6.0 to get the position:
public class MainActivity extends AppCompatActivity implements LocationListener{
protected LocationManager locationManager;
protected LocationListener locationListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkPermission())
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
#Override
public void onLocationChanged(Location location) {
lati = location.getLatitude();
longi = 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");
}
private boolean checkPermission(){
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 false;
}
return true;
}
}
I set the permissions in the programs properties to true.
It used to work but now it never finds satellites or the position in general.
Google maps immediately finds satellites.
What do I need to change?
see all that TODO comment in your code? implement it. you must do this for it to work on modern versions of andorid

Categories

Resources