本文介绍了在广播接收器/或服务中获取 GPS 位置到广播接收器数据传输的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是安卓新手.
我想在广播接收器中获取 GPS 位置,但显示错误.

I am new to android.
I want to get GPS Location in a broadcast receiver but it shows an error.

我的代码是:

public void onReceive(Context context, Intent intent) {
    LocationManager locManager = (LocationManager)
            getSystemService(Context.LOCATION_SERVICE);
    // errors in getSystemService method
    LocationListener locListener = new MyLocationListener();
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            locListener);
    Location loc = locManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);
    Log.d(" **location**", " location" + loc.getLatitude());
}

问题:

  1. 是否可以在广播接收器中获取 GPS 位置数据?
  2. 到目前为止我尝试的另一种替代方法是使用由广播接收器调用的服务.该服务可以获取 GPS 数据,但如何在广播接收器中获取它?

推荐答案

我也无法从 BroadcastReceiver 启动位置管理器.因此,我在 BroadcastReceiver 上启动了一项服务,并在该服务中操作了位置管理器.我想我在 Android 开发文档中找到了这个解决方案.您也可以启动 Activity 而不是 Service.

From BroadcastReceiver I could not start Location Manager as well. So I started a service on BroadcastReceiver and in that service I manipulated Location Manager. I think I found this solution in Android development documentation. You also can start Activity instead of Service.

这是在 BroadcastReceiver 上切换到 Service 的代码:

Here is the code of switch to Service on BroadcastReceiver:

onReceive方法中写这个

write this in onReceive method

    Intent serviceIntent = new Intent(context,MyService.class);
    serviceIntent.putExtra("locateRequest", "locateRequest"); // if you want pass parameter from here to service
    serviceIntent.putExtra("queryDeviceNumber", results[1]);
    context.startService(serviceIntent); //start service for get location

这篇关于在广播接收器/或服务中获取 GPS 位置到广播接收器数据传输的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-27 22:31