2017-02-20 87 views
0

我的應用使用LocationServices來請求位置更新。它通過PendingIntent將結果發送到接收器。在的onReceive()一個LocationResult從意圖,這產生一個位置,其隨後在緯度來表示LNG,有待進一步用於提取。聽起來不錯,對吧?從onReceive()中的LocationResult獲取位置

那麼,應用程序開始崩潰與空指針異常

我調查使用調試器,發現我在上面所描述的三個行代碼執行精細,但隨後,代替進行到下面的代碼行,執行在某種程度上涉及再次回到第一的三行,從意圖中提取LocationResult。現在原來是空的,並在NullPointerException,作爲墜毀在以下行位置結果假定不爲空。

我不知道爲什麼會發生這種情況。任何指針,請? (很抱歉的雙關語)

這裏是我的代碼:

public class MyLocationUpdateReceiver extends BroadcastReceiver { 

    private static final String TAG = "MyLocationUpdateRcvr"; 

// empty constructor 
    public MyLocationUpdateReceiver(){} 

    @Override 
    public void onReceive(Context context, Intent intent) { 

     Log.i(TAG,"onReceive update"); 

     // extract locationResult from intent received from Update Request 
     LocationResult locationResult = LocationResult.extractResult(intent); 
     double locationLat = locationResult.getLastLocation().getLatitude(); 
     double locationLng = locationResult.getLastLocation().getLongitude(); 

     // send the Lat and Lng of new location to MapActivity via intent 
     Intent mIntent = new Intent(context.getApplicationContext(), 
     MapActivity.class); 
     mIntent.putExtra("New_Lat", locationLat); 
     mIntent.putExtra("New_Lng", locationLng); 
     mIntent.addFlags(FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(mIntent); 

    } 
} 

這裏是第一次through.Note的LocationResult不是空的屏幕截圖。

enter image description here

不過在第一次圓...

enter image description here

並在第二次輪...

enter image description here

+0

可能是您的意圖'null'。 – Piyush

+0

第一次不是空的 –

回答

0

我假設你是在清單中註冊時使用您的接收器。你需要使用java編碼的廣播接收器,我的意思是動態綁定。有關如何綁定的詳細信息,請參閱下面的鏈接。

Dynamically registering a broadcast receiver

其次,你可以,你也可以嘗試傳球意圖爲你傳遞LocationResult.extractResult(意圖)代替;在onReceive()方法中評估意圖

+0

我已經在Manifest中註冊了接收器,並且也在我的代碼中動態地註冊了接收器。你的第二點並不清楚你的意思。 –

+0

我想說你應該嘗試在本地使用intent(本地意味着在onReceive的範圍內)。總之不要傳遞其他方法來提取數據使用onReceive方法的邊界 –

+0

如何提取LocationResult從意圖,如果不通過使用extractResult()? –