簡體   English   中英

Android位置更改界面

[英]Android location changed interface

我創建了一個幫助程序類,其中所有位置google play服務功能都已初始化。 onLocationChanged被調用時,我調用接口onLocationChangedFunction 但是由於空指針異常,它從未調用過它。

這是我的代碼:

public class LocationHelperClass implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

private Context mContext;
private TaxiplonApp mApp;
private GoogleApiClient mGoogleApiClient;
private Location mLastLocation;
/**
 * The desired interval for location updates. Inexact. Updates may be more or less frequent.
 */
private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;

/**
 * The fastest rate for active location updates. Exact. Updates will never be more frequent
 * than this value.
 */
private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
        UPDATE_INTERVAL_IN_MILLISECONDS / 2;


/**
 * Stores parameters for requests to the FusedLocationProviderApi.
 */
private LocationRequest mLocationRequest;

public static LocationChangeListener locationListener;

public LocationHelperClass(Context context, TaxiplonApp app) {
    super();
    this.mContext = context;
    this.mApp = app;
    createInstanceGoogleAPIClient();
}

private void createInstanceGoogleAPIClient() {
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }
}

/**
 * Sets up the location request. Android has two location request settings:
 * {@code ACCESS_COARSE_LOCATION} and {@code ACCESS_FINE_LOCATION}. These settings control
 * the accuracy of the current location. This sample uses ACCESS_FINE_LOCATION, as defined in
 * the AndroidManifest.xml.
 * <p/>
 * When the ACCESS_FINE_LOCATION setting is specified, combined with a fast update
 * interval (5 seconds), the Fused Location Provider API returns location updates that are
 * accurate to within a few feet.
 * <p/>
 * These settings are appropriate for mapping applications that show real-time location
 * updates.
 */
protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();

    // Sets the desired interval for active location updates. This interval is
    // inexact. You may not receive updates at all if no location sources are available, or
    // you may receive them slower than requested. You may also receive updates faster than
    // requested if other applications are requesting location at a faster interval.
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);

    // Sets the fastest rate for active location updates. This interval is exact, and your
    // application will never receive updates faster than this value.
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);

    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}

/**
 * Requests location updates from the FusedLocationApi.
 */
protected void startLocationUpdates() {
    // The final argument to {@code requestLocationUpdates()} is a LocationListener
    // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        // TODO: Consider calling
        //    ActivityCompat#requestPermissions
        // here to request the missing permissions, and then overriding
        //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
        //                                          int[] grantResults)
        // to handle the case where the user grants the permission. See the documentation
        // for ActivityCompat#requestPermissions for more details.
        return;
    }
    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}

/**
 * Removes location updates from the FusedLocationApi.
 */
protected void stopLocationUpdates() {
    // It is a good practice to remove location requests when the activity is in a paused or
    // stopped state. Doing so helps battery performance and is especially
    // recommended in applications that request frequent location updates.

    // The final argument to {@code requestLocationUpdates()} is a LocationListener
    // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}


public void clientConnect(){
    mGoogleApiClient.connect();
}

public void clientDisconnect(){
    mGoogleApiClient.disconnect();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mLastLocation != null) {
        Toast.makeText(mContext, "Latitude: "+String.valueOf(mLastLocation.getLatitude())+" - Longtitude: "+String.valueOf(mLastLocation.getLongitude()), Toast.LENGTH_SHORT).show();
        mApp.setLastKnownLocation(mLastLocation);
    }
    startLocationUpdates();
}

@Override
public void onConnectionSuspended(int i) {
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}


@Override
public void onLocationChanged(Location location) {
    DebugLogger.debug("Location Changed called in Helper Class");

    if(locationListener!=null){
        locationListener.onLocationChangedFunction(location);
    }
}

public interface LocationChangeListener {
    void onLocationChangedFunction(Location location);
}

}

我將這個監聽器實現為我的活動,並在onCreate中將其初始化,如下所示:

location = new LocationHelperClass(this, (TaxiplonApp) getApplication());

但是,正如我所說的,在我的活動中從未調用過onLocationChangedFunction

  12-21 17:48:28.100 4634-4634/? E/AndroidRuntime: FATAL EXCEPTION: main
                                             Process: com.taxiplon.taxi.driver.lit.taxiplondriver, PID: 4634
                                             java.lang.NullPointerException: Attempt to invoke interface method 'void com.taxiplon.taxi.driver.lit.taxiplondriver.HelperClasses.LocationHelperClass$LocationChangeListener.onLocationChangedFunction(android.location.Location)' on a null object reference
                                                 at com.taxiplon.taxi.driver.lit.taxiplondriver.HelperClasses.LocationHelperClass.onLocationChanged(LocationHelperClass.java:166)
                                                 at com.google.android.gms.internal.zzart$zzb$1.zza(Unknown Source)
                                                 at com.google.android.gms.internal.zzart$zzb$1.zzs(Unknown Source)
                                                 at com.google.android.gms.internal.zzaaz.zzb(Unknown Source)
                                                 at com.google.android.gms.internal.zzaaz$zza.handleMessage(Unknown Source)
                                                 at android.os.Handler.dispatchMessage(Handler.java:102)
                                                 at android.os.Looper.loop(Looper.java:135)
                                                 at android.app.ActivityThread.main(ActivityThread.java:5294)
                                                 at java.lang.reflect.Method.invoke(Native Method)
                                                 at java.lang.reflect.Method.invoke(Method.java:372)
                                                 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
                                                 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)

偵聽器永遠不會分配值,因此它為null。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM