LcoationChanged не вызывается, когда активность переходит в режим паузы или остановки, когда приложение в стеке в Android Oreo Version - PullRequest
0 голосов
/ 11 июня 2018

Поскольку я использую googleapiclient в своей деятельности для получения местоположения, но когда приложение находится на переднем плане, это означает, что метод onlocationchange работает, поэтому я получаю местоположение.Когда приложение находится в состоянии паузы или остановки, значит местоположение не попадает в версию Android Oreo. Когда действие переходит в состояние уничтожения, значит, хорошо, мы не получим местоположение, потому что оно находится в фоновом режиме, когда приложение в состоянии паузы или остановки означает, что оно должно быть передано другому.активность или в стеке.

Служба не будет вызывать, только когда приложение переходит в спящий режим, но активность должна работать, когда находится в состоянии паузы или остановки, верно?но это не работает в моем приложении. Пожалуйста, помогите мне исправить мою проблему.

public class UserHomePage extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, View.OnClickListener,GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {

    Thread t;
    private Location mylocation;
    private GoogleApiClient googleApiClient;
    private final static int REQUEST_CHECK_SETTINGS_GPS=0x1;
    private final static int REQUEST_ID_MULTIPLE_PERMISSIONS=0x2;
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;
    private RequestQueue requestQueue,requestQueue1,requestQueue2,requestQueue3,requestQueue4;

    String gs_var_fcm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_activity_home);
        ctx=this;
     setUpGClient();

        mapboxToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mapboxToolbar);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.i("WW","--onPause");

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i("WW","--onStop");


        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();


        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }


   private synchronized void setUpGClient() {
        googleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, 0, this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        googleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        mylocation = location;
        if (mylocation != null) {
            Log.i("QES","onlocation"+mylocation);

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        checkPermissions();
    }

    @Override
    public void onConnectionSuspended(int i) {
        //Do whatever you need
        //You can display a message here
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        //You can display a message here
    }

    private void getMyLocation(){
        if(googleApiClient!=null) {
            if (googleApiClient.isConnected()) {
                int permissionLocation = ContextCompat.checkSelfPermission(UserHomePage.this,
                        Manifest.permission.ACCESS_FINE_LOCATION);
                if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                    mylocation =                     LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
                    LocationRequest locationRequest = new LocationRequest();
                    locationRequest.setInterval(3000);
                    locationRequest.setFastestInterval(3000);
                    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
                            .addLocationRequest(locationRequest);
                    builder.setAlwaysShow(true);
                    LocationServices.FusedLocationApi
                            .requestLocationUpdates(googleApiClient, locationRequest, this);
                    PendingResult<LocationSettingsResult> result =
                            LocationServices.SettingsApi
                                    .checkLocationSettings(googleApiClient, builder.build());
                    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {

                        @Override
                        public void onResult(LocationSettingsResult result) {
                            final Status status = result.getStatus();
                            switch (status.getStatusCode()) {
                                case LocationSettingsStatusCodes.SUCCESS:
                                    // All location settings are satisfied.
                                    // You can initialize location requests here.
                                    int permissionLocation = ContextCompat
                                            .checkSelfPermission(UserHomePage.this,
                                                    Manifest.permission.ACCESS_FINE_LOCATION);
                                    if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
                                        mylocation = LocationServices.FusedLocationApi
                                                .getLastLocation(googleApiClient);
                                        if(mylocation!=null)
                                        {
                                            Log.i("QES","permissionlocation"+mylocation);

                                            //  Toast.makeText(UserHomePage.this, "mylocation"+mylocation, Toast.LENGTH_SHORT).show();
                                            gs_str_latitude = String.valueOf(mylocation.getLatitude());
                                            gs_str_Longitude = String.valueOf(mylocation.getLongitude());
                                            sharedPreferences = getSharedPreferences("myprefer", MODE_PRIVATE);
                                            editor = sharedPreferences.edit();

                                            editor.putString("dest_Lat", gs_str_latitude);
                                            editor.putString("dest_Long", gs_str_Longitude);
                                            editor.putString("Lat", gs_str_latitude);
                                            editor.putString("Long", gs_str_Longitude);

                                            editor.commit();

                                            GS_UserUpdateLocation(gs_str_latitude, gs_str_Longitude, strlevel, Date, networkinformation);

                                        }
                                        else
                                        {
                                            //  Toast.makeText(UserHomePage.this, "mylocation", Toast.LENGTH_SHORT).show();

                                        }

                                    }
                                    break;
                                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                                    // Location settings are not satisfied.
                                    // But could be fixed by showing the user a dialog.
                                    try {
                                        // Show the dialog by calling startResolutionForResult(),
                                        // and check the result in onActivityResult().
                                        // Ask to turn on GPS automatically
                                        status.startResolutionForResult(UserHomePage.this,
                                                REQUEST_CHECK_SETTINGS_GPS);
                                    } catch (IntentSender.SendIntentException e) {
                                        // Ignore the error.
                                    }
                                    break;
                                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                                    // Location settings are not satisfied.
                                    // However, we have no way
                                    // to fix the
                                    // settings so we won't show the dialog.
                                    // finish();
                                    break;
                            }
                        }
                    });
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS_GPS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        getMyLocation();
                        break;
                    case Activity.RESULT_CANCELED:
                        finish();
                        break;
                }
                break;
        }
    }

    private void checkPermissions(){
        int permissionLocation = ContextCompat.checkSelfPermission(UserHomePage.this,
                android.Manifest.permission.ACCESS_FINE_LOCATION);
        List<String> listPermissionsNeeded = new ArrayList<>();
        if (permissionLocation != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(android.Manifest.permission.ACCESS_FINE_LOCATION);
            if (!listPermissionsNeeded.isEmpty()) {
                ActivityCompat.requestPermissions(this,
                        listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
            }
        }else{
            getMyLocation();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        int permissionLocation = ContextCompat.checkSelfPermission(UserHomePage.this,
                Manifest.permission.ACCESS_FINE_LOCATION);
        if (permissionLocation == PackageManager.PERMISSION_GRANTED) {
            getMyLocation();
        }
    }

Примечание: хотя я даю googleapiclient подключен только тогда, когда пауза, остановка, возобновление, состояние запуска, даже если он не отображается.пожалуйста, помогите мне

1 Ответ

0 голосов
/ 11 июня 2018

Из Oreo, Google добавил ограничения, чтобы получить местоположение, когда приложение находится в фоновом режиме.Вы можете прочитать изменения, внесенные в Oreo здесь.

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

...