2017-02-20 86 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()? –