我有一个LocationActivity,可以从Google API获取GPS位置。我需要在MainActivity中使用此数据。我正在使用startActivityForResult来完成此操作,但是我尝试访问数据时,LocationActivity从不执行,并且应用程序崩溃。

这是MainActivity.java的一些相关片段:

public void onUpdateClick(View v) { //button click handler which starts the process

    Intent i = new Intent(MainActivity.this, LocationActivity.class);
    startActivityForResult(i, GPS_DATA_REQUEST);

    byte[] data = latitude.getBytes(); //app crashes here because latitude is null
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == GPS_DATA_REQUEST) {
        if(resultCode == Activity.RESULT_OK){
            latitude=data.getStringExtra("latitude");
        }
    }
}


以下是LocationActivity.java的相关片段:

@Override
public void onConnected(Bundle bundle) {
    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);


    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
            mGoogleApiClient);
    if (mLastLocation != null) {
        latitude = String.valueOf(mLastLocation.getLatitude());
    }

    Intent returnIntent = new Intent();
    returnIntent.putExtra("latitude",latitude);
    setResult(LocationActivity.RESULT_OK, returnIntent);
    finish();
}


而我的Android清单:

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme">
    <activity
        android:name=".MainActivity"
        android:label="@string/label_broadcast">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".LocationActivity">
    </activity>
</application>




我已经提到了许多线程和Android活动/意图文档,但无法解决此问题。任何帮助/建议,将不胜感激。我尝试仅提供相关信息。谢谢!

最佳答案

将LocationActivity中的代码从onConnected移到onStart。 startActivityForResult调用onStart生命周期方法。

10-08 07:13