Search code examples
androidgpslocationmanagerlocationlistener

LocationManager won't start after re-opening app


I'm working on a project which determines periodically the phone's coordinates and uploads them on a Database. The code I'm using is:

public class Activity2 extends AppCompatActivity {

private LocationManager locm;
private LocationListener locl;
private Geocoder geocoder;
public TextView text, position;
public double lat, lon;
public String city;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_2);
    text = (TextView) findViewById(R.id.textView4);
    position = (TextView) findViewById(R.id.textView5);

    text.setText("Seriale: " + Build.SERIAL + "\nNome: " + Build.MANUFACTURER + " " + Build.PRODUCT);
    geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
    locm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locl = new LocationListener(){
        @Override
        public void onLocationChanged(Location location) {
            try{
                lat=location.getLatitude();
                lon=location.getLongitude();
                DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String date = df.format(Calendar.getInstance().getTime());
                List<Address> la = geocoder.getFromLocation(lat, lon, 1);
                if (la != null & la.size() > 0) {
                    Address address = la.get(0);
                    city = address.getLocality();
                }
                else
                {
                    city="UNKNOWN";
                }
                MainActivity.st.executeUpdate("INSERT INTO position VALUES ('" + Build.SERIAL + "', '" + date + "', '" + lat + "', '" + lon + "', '" +city + "')");
                position.setText(city);
            } catch (Exception a){

            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

    };

    if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
        if(checkSelfPermission(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_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION,
                   Manifest.permission.INTERNET
           }, 10);
            return;
        }
    }else{
        locm.requestLocationUpdates("gps", 5000, 0, locl);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode){

        case 10:
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED) {
                try{
                    locm.requestLocationUpdates("gps", 5000, 0, locl);
                }catch (SecurityException e){

                }
            }
    }
}

From a clean start (no cache/data about the app saved before) it runs good and works as expected:

  • Starts the first activity which is a simple login (if usertext=user $$ passtext=text starts Activity2)
  • Activity2 asks for permissions (and GPS if it's disabled)
  • Waits for GPS to discover its first position
  • Uploads positions every 5 seconds

But if I close the app (not pressing back button but cleaning it from RAM) and then I try to open it again, after starting of Activity2 it doesn't ask me for enabling GPS anymore and it doesn't show positions anymore even if it's already enabled. The only way to get it back to work is cleaning data from internal storage memory.

How can I solve this problem? Thank you.


Solution

  • The problem is when Build.VERSION.SDK_INT >= Build.VERSION_CODES.M is true and you already have the required permissions, you don't call requestLocationUpdates().

    Try the following:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        if (checkSelfPermission(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_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
                            Manifest.permission.INTERNET }, 10);
            return;
        } else {
            // you are missing this else block
            locm.requestLocationUpdates("gps", 5000, 0, locl);
        }
    } else {
        locm.requestLocationUpdates("gps", 5000, 0, locl);
    }