首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从onReceive()中的LocationResult中获取位置

从onReceive()中的LocationResult中获取位置
EN

Stack Overflow用户
提问于 2017-02-20 20:45:46
回答 2查看 894关注 0票数 0

我的应用程序使用LocationServices请求位置更新。它通过PendingIntent将结果发送到Receiver。在onReceive()中,从intent中提取一个LocationResult,它产生一个Location,然后用LatLng表示,以便进一步使用。听起来不错,对吧?

好吧,这个应用程序开始在NullPointerException.上崩溃

我使用调试器进行了调查,发现上面描述的三行代码执行得很好,但是随后,执行没有继续到下面的代码行,而是以某种方式重新定向到这三行代码中的第一行,这三行代码从意图中提取了一个LocationResult。这现在被证明是null,并且由于假设LocationResult不是null,所以在具有NullPointerException,的以下行上崩溃。

我不知道为什么会发生这种事。有什么建议吗?(很抱歉我的双关语)

下面是我的代码:

代码语言:javascript
复制
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不为空的截图。

还在第一轮。

在第二轮的时候...

EN

回答 2

Stack Overflow用户

发布于 2019-05-17 03:12:40

有没有将额外服务放到PendingIntent中的场景?经过一些测试后,我发现这会导致位置信息在传递给接收方时不会存储在intent中。看起来他们应该能够在你的意图中将位置放在额外的位置旁边,但它不是以这种方式实现的。

票数 1
EN

Stack Overflow用户

发布于 2017-02-20 21:14:31

我假设你在清单中注册时正在使用你的接收器。你需要使用带有java编码的广播接收器,我的意思是动态绑定。有关如何绑定的详细信息,请参阅下面的链接。

Dynamically registering a broadcast receiver

其次,您还可以尝试在传递LocationResult.extractResult( intent )时不传递intent;在onReceive()方法中计算intent

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42344963

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档