Я хотел бы ответить на свой вопрос.
Я не использовал метод requestPermissions () в моем коде выше и даже имел неправильный вид разрешения в операторе if.
Я также не знал, как работают методы requestLocationUpdates () и метод обратного вызова onRequestPermissionsResult (). (Ctrl + Q помог здесь)
package com.example.gpstryxyz;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
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.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements LocationListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//app seemed to work only with gps, but does not update during runtime, quit and restart app to get new location
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationManager locationManager;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
//registration (if this call succeeds, it calls the onLocationChanged() method)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this);
} else {
TextView tv = (TextView) findViewById(R.id.gpsTextView);
tv.setText(R.string.noPermission);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) throws SecurityException{
if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission is granted
LocationManager locationManager;
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 10, this);
}
}
@Override
public void onLocationChanged(Location location) {
//the Location object this method brings has the location data in it
double value1 = location.getLatitude();
double value2 = location.getLongitude();
TextView tv = (TextView) findViewById(R.id.gpsTextView);
tv.setText(getString(R.string.latlonString, String.valueOf(value1), String.valueOf(value2)));
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "gps is activated.....", Toast.LENGTH_LONG).show();
}
@Override
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "gps is NOT activated.....", Toast.LENGTH_LONG).show();
}
}