0

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?

  • The debugger in android works great so I'd suggest stepping through. Gratuitous use of `Log.d` can show problems too. On a specific level maybe check that you're actually getting non-null from your sensor calls. – Richard Nixon May 11 '20 at 12:42

1 Answers1

0

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.