android - 即使在 android 中使用 Fused Location API 时将上下文传递给 GoogleApiClient,GoogleApiClient 也会给出空指针

标签 android nullpointerexception android-fusedlocation android-googleapiclient

我正在尝试在服务中实现 Fused Location API。我已经完成了以下编码,但出现如下错误:

  java.lang.RuntimeException: Unable to instantiate service com.locate.LocationDetails: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Looper android.content.Context.getMainLooper()' on a null object reference

在下面的代码行:

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

我的代码如下:

public class LocationDetails extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;
    Broadcaster broadcaster;
    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    @Override
    public void onCreate() {
        super.onCreate();



    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);

    }

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

        return super.onStartCommand(intent, flags, startId);
    }

    public LocationDetails() {
        // super();
      mGoogleApiClient = new GoogleApiClient.Builder(getBaseContext())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();


        mGoogleApiClient.connect();
      /*  mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000);*/
        Log.i("Service", "Started");


    }

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

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onConnected(Bundle bundle) {

        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

        if (location == null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
        } else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i("Connection", "Suspended");

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

        if (connectionResult.hasResolution()) {
            try {

                connectionResult.startResolutionForResult((Activity) getBaseContext(), CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {
            Log.i("connection err", "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    private void handleNewLocation(Location location) {
        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();
        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        Log.i("location", "" + latLng);


    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i("On Changd Location", "" + location.getLatitude());

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        Log.i("Provider", provider);

    }

    @Override
    public void onProviderDisabled(String provider) {

    }
}

我正在传递一个 context 但仍然是 NullPointer Exception

谁能告诉我如何修复此崩溃并更正 mt 代码,其次我怀疑 fused location api 是否可以与服务一起使用?

最佳答案

您收到 NullPointerException 的原因是您在构造函数中调用了 getBaseContext()

这相当于this.getBaseContext(),此时this不能作为Context。

更多信息 here .

只需将代码从构造函数移动到onCreate():

@Override
public void onCreate() {
    super.onCreate();

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


    mGoogleApiClient.connect();

    Log.i("Service", "Started");

}

关于android - 即使在 android 中使用 Fused Location API 时将上下文传递给 GoogleApiClient,GoogleApiClient 也会给出空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30205732/

相关文章:

c# - 将 Windows Phone 应用程序移植到 Android

JavaFx ListView<Float> 设置所有元素的字体颜色

java - 什么是NullPointerException,我该如何解决?

android - 有什么好的策略来处理 O 设备上运行的应用程序的后台位置限制?

android - 打开/关闭位置时,FusedLocationProviderClient 无法正常工作

java - 安卓系统应用权限

android - Gridview 没有正确显示为 Listview 的标题

android - 在 Android 中单击按钮时的帧动画

android - 从图库中选择视频时,Android 10 像素 2 中出现无效的列纬度错误

android - onLocationChanged 在应用程序启动时被多次调用