在Custom Listner的服务中使用ActivityContext

时间:2018-05-29 05:27:39

标签: android performance android-activity service android-context

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;
                    }


                }
            });
}



}

这行代码给我带来了一个问题,因为它需要Activity上下文,当它不是一个服务而我传递活动上下文时它是完美的。

  

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 :(得分:0)

首先,您的应用程序类没有实现LocationListener接口,因此您收到此错误。您无法在意图服务中获取Activity实例,因为1)它可能不再处于活动状态2)Intent Service可以从其他服务或广播接收器启动。为了将LocationListener方法与您的活动进行通信,您需要使用LocalBroadcastManager