尝试使用GoogleApiClient在null对象引用上调用android.os.Looper

时间:2016-10-19 18:53:39

标签: java android-studio nullreferenceexception android-looper

我正在尝试将我的应用程序转换为服务,因此无法轻松销毁它并保持运行。我已经多次移动代码试图找出它的正确位置以便于使用,但现在我得到了

  

java.lang.NullPointerException:尝试调用接口方法' android.os.Looper com.google.android.gms.common.api.GoogleApiClient.getLooper()'在空对象引用上

它发生在这个代码块中:

public void initiateMockLocs() {
    Location mockLoc = new Location(LocationManager.NETWORK_PROVIDER);
    mockLoc.setLatitude(41.881832);
    mockLoc.setLongitude(-87.623177);
    mockLoc.setAccuracy(20);
    mockLoc.setTime(System.currentTimeMillis());
    mockLoc.setElapsedRealtimeNanos(System.nanoTime());

    try {
        LocationServices.FusedLocationApi.setMockMode(mMainActivity.mGoogleApiClient, true);
        LocationServices.FusedLocationApi.setMockLocation(mMainActivity.mGoogleApiClient, mockLoc);

        Location loc = LocationServices.FusedLocationApi.getLastLocation(mMainActivity.mGoogleApiClient);
        Log.i("Mock Location: ", loc.toString());

        Log.i("Timer", "Going to start timer.");
        logLocation();
        startTimer();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

具体来说,在"下的第一行尝试"块。该函数是我在此服务的onCreate中调用的唯一函数,因此在那里调用它。初始化mGoogleApiClient的其他一些背景信息是:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayShowTitleEnabled(true);

    createLocationRequest();
    buildGoogleApiClient();
    mGoogleApiClient.connect();

    showProcesses = (Button) findViewById(R.id.listApps);
    showProcesses.setOnClickListener(listRunningApps);

    activateMockLocs = (Button) findViewById(R.id.activateMock);
    activateMockLocs.setOnClickListener(activateMockLocations);

    latView = (TextView) findViewById(R.id.latView);
    longView = (TextView) findViewById(R.id.longView);

    anonymizationService = new AnonymizationService();
}

protected synchronized void buildGoogleApiClient() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .build();
}
// Initialize a LocationRequest object
protected void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(10000);
    mLocationRequest.setFastestInterval(10000);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}

如果有人知道让MainActivity与服务部门交流并解决这个问题的正确方法,那就太棒了!我似乎无法找到解决我的确切问题的答案。提前谢谢。

0 个答案:

没有答案