我有一個LocationActivity可以從Google API獲取GPS位置。我需要在我的MainActivity中使用這些數據。我正在使用startActivityForResult來完成此操作,但是當我嘗試訪問數據時,我的LocationActivity從不執行,並且我的應用程序崩潰。startActivityForResult沒有開始第二個活動
這裏是從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活動/意圖文檔,但一直未能解決這個問題。任何幫助/建議,將不勝感激。我曾嘗試僅提供相關信息。謝謝!
發佈你的logcat – sasikumar
你不能期望在'startActivityForResult'之後立即得到結果。結果將在'onActivityResult'中被接收。 Android基礎知識 – SMR
@SMR說你不能在'startActivityForResult'之後立即得到結果。你需要在'onActivityResult'中獲得你的緯度,所以當你接收到緯度時,'onActivityResult'方法中的其他代碼會再次請求緯度。 – Shailesh