【问题标题】:Retrieving location updates in Service in Android在 Android 的 Service 中检索位置更新
【发布时间】:2013-09-23 12:39:23
【问题描述】:

我尝试通过网络提供商检索服务中的位置更新,但更新无法执行。我的代码如下所示:

public class TimeService extends Service{

LocationManager lm;
LocationListener ll = new LocationListener()
{

    @Override
    public void onLocationChanged(Location location) {

        double latitude = location.getLatitude();
        double longtitude = location.getLongitude();

        Intent inte =new Intent( TimeService.this, myAppWidgetProvider.class);
        inte.setAction("action_location");
        inte.putExtra("lat", latitude);
        inte.putExtra("long", longtitude);

        PendingIntent pinte = PendingIntent.getBroadcast(TimeService.this, 0, inte, 0);

        try {
            pinte.send();
        } catch (CanceledException e) {
            // TODO Auto-generated catch block
            Log.d("sendPIException", ":-(");
        }

        Log.d("locReceived", "onLochanged");

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status,
            Bundle extras) {
        // TODO Auto-generated method stub

    }

};

在 onLocationChanged 中的日志“locReceived”没有出现我 logcat 以下代码也负责我的服务中的位置:

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        this.registerReceiver(br, new IntentFilter(Intent.ACTION_TIME_TICK));
        lm =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll);
        return super.onStartCommand(intent, flags, startId);
    }

我的代码有什么问题?

【问题讨论】:

  • 检查清单上的适当权限。
  • 我拥有 access_coarse_location、access_fine_location 和 Internet 权限,并且我也在清单中声明了服务。
  • 别恨我,但你是用 startService() 开始你的服务吗?
  • 是的 :) 我的服务功能可以每分钟更新一次时间,它正在工作

标签: android service location


【解决方案1】:
Criteria criteria = new Criteria();

String provider = lm.getBestProvider(criteria, false);
Location location = lm.getLastKnownLocation(provider);

lm.requestLocationUpdates(provider, 0, 0, ll);

if (location == null) {
    Log.e("Impl", "Location not available");
}

【讨论】:

  • 尝试在行中使用this.getApplicationContext() 而不是this lm =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
  • 尝试我的最后一个可以帮助的选项,顺便说一句,将日志添加到所有其他 4 种方法:onProviderEnabled ....
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-10
  • 2020-10-10
相关资源
最近更新 更多