Невозможно получить местоположение в первый раз с услугой определения местоположения при запуске приложения - PullRequest
0 голосов
/ 09 мая 2019

Я использую сервис для получения текущего местоположения, оно выбирает местоположение каждый раз, когда приложение запускается, за исключением самого первого раза. Поскольку самый первый метод onConnected называется logs, получайте также печать в log cat, но после этого ни один метод невызываемое местоположение не извлекается и ничего не происходитЛюбая помощь будет оценена.

public class LocationUpdateService extends Service implements GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private Context mContext;
    Location mLocation;
    GoogleApiClient mGoogleApiClient;

    public double lattitude = 0.0, longitude = 0.0;

    private LocationRequest mLocationRequest;
    private long UPDATE_INTERVAL = 40 * 1000;
    private long FASTEST_INTERVAL = 20 * 1000;

    public static String LOCATION_UPDATE_BROADCAST = "com.demo";

    private static final String TAG = LocationUpdateService.class.getSimpleName();

    @Override
    public void onCreate() {
        showLog("onCreate");

        mContext = LocationUpdateService.this;

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);

        showLog("onStart");

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

    @Override
    public void onConnected(Bundle bundle) {
        showLog("onConnected");/* Always called but nothing happen after it */

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if(mLocation!=null)
        {
            Log.e("latitude--", String.valueOf(mLocation.getLatitude()));
            try
            {
                lattitude = mLocation.getLatitude();
                longitude = mLocation.getLongitude();
            }
            catch (Exception ex)
            {
                showLog("Exception = "+ex.getMessage());
            }

            if(lattitude != 0.0 && longitude != 0.0)
            {
                //Here set latitude longitude in prefreance when get new lattitude longitude
                Session.setLatitude(mContext, String.valueOf(lattitude));
                Session.setLongitude(mContext, String.valueOf(longitude));


                Geocoder geocoder = new Geocoder(mContext);

                try {

                    List<Address> addresses = geocoder.getFromLocation(lattitude,longitude,1);

                    if(addresses != null && addresses.size() >0)
                    {
                        String country_name = addresses.get(0).getCountryName();
                        ProjectUtils.showLog(TAG,""+country_name);
                        Session.setCountry_name(mContext,country_name);
                    }

                }catch (IOException e)
                {
                    e.printStackTrace();
                }
                Intent intent = new Intent(LocationUpdateService.LOCATION_UPDATE_BROADCAST);
                intent.setPackage(mContext.getPackageName());
                mContext.sendBroadcast(intent);
            }else
            {
            }
        }

        startLocationUpdates();
    }

    @Override
    public void onConnectionSuspended(int i)
    {
        showLog("onConnectionSuspended");
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult)
    {
        showLog("onConnectionFailed");
    }

    @Override
    public void onLocationChanged(Location location)
    {
        showLog("onLocationChanged");

        if(location!=null)
        {
            try
            {
                lattitude = location.getLatitude();
                longitude = location.getLongitude();
            }
            catch (Exception ex)
            {
                showLog("Exception = "+ex.getMessage());
            }

            if(lattitude != 0.0 && longitude != 0.0)
            {
                //Here again set location in prefreance if latitude longitude changes
                Session.setLatitude(mContext, String.valueOf(lattitude));
                Session.setLongitude(mContext, String.valueOf(longitude));

                Intent intent = new Intent(LocationUpdateService.LOCATION_UPDATE_BROADCAST);
                intent.setPackage(mContext.getPackageName());
                mContext.sendBroadcast(intent);
            }
        }
    }

    @SuppressLint("RestrictedApi")
    protected void startLocationUpdates()
    {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);

        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }


    @Override
    public void onDestroy()
    {
        super.onDestroy();
        showLog("Service Stop");
        stopLocationUpdates();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    public void stopLocationUpdates()
    {
        if (mGoogleApiClient.isConnected())
        {
            LocationServices.FusedLocationApi
                    .removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void showLog(String text)
    {
        Log.e(TAG,text);
    }
}
...