Использовать ActivityContext в сервисе для Custom Listner - PullRequest
0 голосов
/ 29 мая 2018

PrimaryDashBoard, где я использую LocatinListener и извлекаю местоположение из сервиса

public class PrimaryDashboard extends AppCompatActivity implements LocationListener {
public LatLng myLatLng=new LatLng(0.0,0.0);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_primary_dashboard);

        try {
           Intent i = new Intent(this, LocationManager.class);

            startService(i);

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

@Override
public void onLocationChanged(Location location) {
    myLatLng=new LatLng(location.getLatitude(),location.getLongitude());

}

@Override
public void GPSDisabled(String errorMessage) {

}

@Override
public void GPSEnabled() {
}
 }

Вот LocationListner

    public interface LocationListener {
   public void onLocationChanged(Location location);

public  void GPSDisabled(String errorMessage);

public void GPSEnabled();
  }

Вот мой сервис, где я хочу инициализировать LocationListner и хочуобновить значения местоположения из списков

   public class LocationManager extends IntentService {
private static final String TAG = LocationManager.class.getSimpleName();
// Registered callbacks
public LocationListener locationUpdate;
public static final int REQUEST_CHECK_SETTINGS = 0x1;
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
        UPDATE_INTERVAL_IN_MILLISECONDS / 2;

private FusedLocationProviderClient mFusedLocationClient;
private SettingsClient mSettingsClient;
private LocationRequest mLocationRequest;
private LocationSettingsRequest mLocationSettingsRequest;
private LocationCallback mLocationCallback;
private Location mCurrentLocation;
private Boolean mRequestingLocationUpdates = false;

@SuppressLint("ServiceCast")
@Override
public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        this.locationUpdate = (LocationListener)  getApplicationContext();

    mRequestingLocationUpdates = false;
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
    mSettingsClient = LocationServices.getSettingsClient(getApplicationContext());

    createLocationCallback();
    createLocationRequest();
    buildLocationSettingsRequest();

    if (!mRequestingLocationUpdates) {
        mRequestingLocationUpdates = true;
        startLocationUpdates();
    }

    return START_STICKY;
}

@Override
protected void onHandleIntent(@Nullable Intent intent) {

}

@SuppressLint("ServiceCast")
@Override
public void onCreate() {

    super.onCreate();
}

public LocationManager() {
    super("locationManager");

}

private void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

/**
 * Creates a callback for receiving location events.
 */
private void createLocationCallback() {
    mLocationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(LocationResult locationResult) {
            super.onLocationResult(locationResult);
            mCurrentLocation = locationResult.getLastLocation();
            PrefManager.getInstance(getApplicationContext()).setLastLatLng(Double.valueOf(locationResult.getLastLocation().getLatitude()), Double.valueOf(locationResult.getLastLocation().getLongitude()));
            if (locationUpdate != null)
                locationUpdate.onLocationChanged(locationResult.getLastLocation());
        }
    };
}


private void buildLocationSettingsRequest() {
    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
    builder.addLocationRequest(mLocationRequest);
    mLocationSettingsRequest = builder.build();
}


private void startLocationUpdates() {

    // Begin by checking if the device has the necessary location settings.
    mSettingsClient.checkLocationSettings(mLocationSettingsRequest)
            .addOnSuccessListener(new OnSuccessListener<LocationSettingsResponse>() {
                @SuppressLint("MissingPermission")
                @Override
                public void onSuccess(LocationSettingsResponse locationSettingsResponse) {

                    LogCat.show("All location settings are satisfied.");
                    if (locationUpdate != null)
                        locationUpdate.GPSEnabled();
                    mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                    int statusCode = ((ApiException) e).getStatusCode();
                    switch (statusCode) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            if (locationUpdate != null)
                                locationUpdate.GPSDisabled("Location settings are not satisfied. Attempting to upgrade location settings ");
                            LogCat.show("Location settings are not satisfied. Attempting to upgrade location settings ");
                            try {
                                // Show the dialog by calling startResolutionForResult(), and check the
                                // result in onActivityResult().
                                ResolvableApiException rae = (ResolvableApiException) e;
                                rae.startResolutionForResult((Activity) getApplicationContext(), REQUEST_CHECK_SETTINGS);
                            } catch (IntentSender.SendIntentException sie) {
                                Log.i(TAG, "PendingIntent unable to execute request.");
                            }
                            break;
                        case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                            String errorMessage = "Location settings are inadequate, and cannot be " +
                                    "fixed here. Fix in Settings.";
                            LogCat.show(errorMessage);
                            if (locationUpdate != null)
                                locationUpdate.GPSDisabled(errorMessage);
                            Toast.makeText(getApplicationContext(), errorMessage, Toast.LENGTH_LONG).show();
                            mRequestingLocationUpdates = false;
                    }


                }
            });
}



}

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

this.locationUpdate = (LocationListener) getApplicationContext ();

 Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to driver.com.driver.LocationComponents.LocationListener

java.lang.RuntimeException: Unable to create service driver.com.driver.LocationComponents.LocationManager: java.lang.ClassCastException: android.app.Application cannot be cast to driver.com.driver.LocationComponents.LocationListener

1 Ответ

0 голосов
/ 29 мая 2018

Во-первых, класс вашего приложения не реализует интерфейс LocationListener, поэтому вы получаете эту ошибку.Вы не можете получить экземпляр Activity внутри вашей службы намерений, потому что 1) он может больше не быть активным 2) Служба Intent может быть запущена из других служб или получателей рассылки.Чтобы связать методы LocationListener с вашей деятельностью, вам необходимо использовать LocalBroadcastManager .

...