Как перезапустить или обновить активность после разрешений ACTION_LOCATION_SOURCE_SETTINGS - PullRequest
0 голосов
/ 26 мая 2020

Я новый разработчик приложения .. Я пытаюсь добавить карту Google в свое приложение, но столкнулся с одной проблемой. Если мой GPS уже работает, когда я открываю активность, я могу получить долготу и широту. Но если GPS не включен, и я открываю действие, и мне открывается окно разрешений, и я перехожу от активности к настройкам и включаю GPS после включения GPS из настройки телефона и возврата к активности, активность не обновляется, пока я не получу долгота и широта.

Как это работает сейчас: Теперь мне нужно выйти из активности и войти снова, теперь он обновлен, и я могу получить данные о долготе и широте.

что я пробую что делать?: мне нужно обновить активность после включения GPS, когда я go вернулся к активности, которую я обнаружил, было обновлено таким образом. или Если нет решения для обновления активности в соответствии с первым решением. сразу после того, как пользователь включит GPS, пользователь не вернется к той же активности, но он будет go к предыдущей активности, а затем, когда он снова щелкнет, чтобы войти в ту же активность, он найдет данные.

Я использую этот код

public class SendMapLactiontest extends AppCompatActivity implements OnMapReadyCallback {



    private static final String TAG = SendMapLactiontest.class.getSimpleName();
    private GoogleMap mMap;

    LocationManager locationManager;
    private CameraPosition mCameraPosition;


    private PlacesClient mPlacesClient;


    private FusedLocationProviderClient mFusedLocationProviderClient;

    private final LatLng mDefaultLocation = new LatLng(-33.8523341, 151.2106085);
    private static final int DEFAULT_ZOOM = 15;


    private Location mLastKnownLocation;


    private static final String KEY_CAMERA_POSITION = "camera_position";
    private static final String KEY_LOCATION = "location";


    private static final int M_MAX_ENTRIES = 5;

    EditText textLatitude,textLongitude,lonTextView,lonTextView1;
    Button button,btn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
            mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
        }

        setContentView(R.layout.map_send_lcation);
        textLatitude=findViewById(R.id.textLatitude);
        textLongitude=findViewById(R.id.textLongitude);
        lonTextView =findViewById(R.id.tap_text1);
        lonTextView1 =findViewById(R.id.tap_text);

        String apiKey = getString(R.string.google_map_api_key);
        Places.initialize(getApplicationContext(), apiKey);
        mPlacesClient = Places.createClient(this);

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);mapFragment.getMapAsync(this);



        if(!isLocationEnabled()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(SendMapLactiontest.this);
            builder.setTitle("R.string.network_not_enabled")
                    .setMessage("R.string.open_location_settings")
                    .setPositiveButton("R.string.yes",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

                                }
                            })
                    .setNegativeButton("R.string.cancel",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                    Intent imgListIntent = new Intent(SendMapLactiontest.this, AddNewItem.class);
                                    startActivity(imgListIntent);
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        if (mMap != null) {
            outState.putParcelable(KEY_CAMERA_POSITION, mMap.getCameraPosition());
            outState.putParcelable(KEY_LOCATION, mLastKnownLocation);
            super.onSaveInstanceState(outState);
        }
    }



    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;
        mMap.clear();


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            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); // 1 is requestCode
                return;

            }
        }else{


        }







        getDeviceLocation();
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);







    }

    protected boolean isLocationEnabled(){
        String le = Context.LOCATION_SERVICE;
        locationManager = (LocationManager) getSystemService(le);
        if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){

            return false;
        } else {

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

            case 1:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED){
                    Toast.makeText(SendMapLactiontest.this,"PERMISSION_DENIED",Toast.LENGTH_SHORT).show();
                    Intent imgListIntent = new Intent(SendMapLactiontest.this, AddNewItem.class);
                    startActivity(imgListIntent);
                    finish();
                }
                else {
                    Toast.makeText(SendMapLactiontest.this,"PERMISSION_GRANTED",Toast.LENGTH_SHORT).show();
                    mMap.setMyLocationEnabled(true);
                    mMap.getUiSettings().setMyLocationButtonEnabled(true);
                    getDeviceLocation();

                    // permission granted do something
                }
                break;
        }
    }

    private void getDeviceLocation() {
            try {
                Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
                locationResult.addOnCompleteListener(this, new OnCompleteListener<Location>() {

                    @Override
                    public void onComplete(@NonNull Task<Location> task) {
                        if (task.isSuccessful()) {
                            mLastKnownLocation = task.getResult();
                            try {
                                if (mLastKnownLocation==null){
                                    isLocationEnabled();


                                }else {

                            textLatitude.setText("" + mLastKnownLocation.getLatitude());
                            textLongitude.setText("" + mLastKnownLocation.getLongitude());
                                if (mLastKnownLocation != null) {

                                    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                            new LatLng(mLastKnownLocation.getLatitude(),
                                                    mLastKnownLocation.getLongitude()), DEFAULT_ZOOM));

                                }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                        } else {

                            Log.d(TAG, "Current location is null. Using defaults.");
                            Log.e(TAG, "Exception: %s", task.getException());
                            mMap.moveCamera(CameraUpdateFactory
                                    .newLatLngZoom(mDefaultLocation, DEFAULT_ZOOM));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);


                        }
                    }
                });

            } catch (SecurityException e) {
                Log.e("Exception: %s", e.getMessage());
            }

    }





}

Итак, если кто-нибудь знает, как можно обновить активность или другое решение, пожалуйста, помогите мне

Я долгое время искал решение проблемы, но все решения у меня не работали.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...