Android服务位置监听器未激活。

3

我已经实现了一个在Android启动时启动的服务:

MyService.java
package com.example.testservicelogging;

import com.example.testservicelogging.MyBroadcastReceiver;

import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;


public class MyService extends Service implements LocationListener {

    LocationManager lm;
    PendingIntent pendingIntent;
    LocationListener locationListener;

    public MyService() {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
        //TODO do something useful
        //Toast.makeText(getBaseContext(), "Got in!!!", Toast.LENGTH_SHORT).show();
        System.out.println("Got in");

         Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();        

            //---use the LocationManager class to obtain locations data---
            lm = (LocationManager)
                    getSystemService(Context.LOCATION_SERVICE);


            Intent i = new Intent(this, MyBroadcastReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(
                    this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);

          //---request for location updates using GPS---
            lm.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER,
                    6000,
                    5,
                    pendingIntent);     

        return START_STICKY;
      }


    @Override
    public void onDestroy() {
        //---remove the pending intent---
        lm.removeUpdates(pendingIntent);

        super.onDestroy();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();        
    }

    @Override
    public void onLocationChanged(Location arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onLocationChanged", Toast.LENGTH_LONG).show();   

    }

    @Override
    public void onProviderDisabled(String arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onProviderDisabled", Toast.LENGTH_LONG).show();   

    }

    @Override
    public void onProviderEnabled(String arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onProviderEnabled", Toast.LENGTH_LONG).show();   

    }

    @Override
    public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "onStatusChanged", Toast.LENGTH_LONG).show();   

    }


}

还有一个BroadcastReceiver类:

package com.example.testservicelogging;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.util.Log;
import android.widget.Toast;


public class MyBroadcastReceiver extends BroadcastReceiver {

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


        Intent t=new Intent(context, MyService.class);
        t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startService(t);

        String locationKey = LocationManager.KEY_LOCATION_CHANGED;
        String providerEnabledKey = LocationManager.KEY_PROVIDER_ENABLED;

        //Toast.makeText(context, "INSIDE!!!", Toast.LENGTH_SHORT).show(); 
        System.out.println("INSIDE");

        if (intent.hasExtra(providerEnabledKey)) {
            if (!intent.getBooleanExtra(providerEnabledKey, true)) {
                Toast.makeText(context,
                        "Provider disabled",
                        Toast.LENGTH_SHORT).show();              
            } else {
                Toast.makeText(context,
                        "Provider enabled",
                        Toast.LENGTH_SHORT).show();
            }
        }

        if (intent.hasExtra(locationKey)) {
            Location loc = (Location)intent.getExtras().get(locationKey);
            Toast.makeText(context,
                    "Location changed : Lat: " + loc.getLatitude() +
                    " Lng: " + loc.getLongitude(),
                    Toast.LENGTH_SHORT).show();



            //do something with the coordinates returned


        }

    }


}

我面临一些问题:
  1. (最重要的):服务在启动时加载,但即使我看到GPS图标闪烁,它也从未返回坐标!!!我做错了什么?
  2. 我想按预定的时间间隔获取坐标(例如每天从08:00到18:00每15分钟一次)。我该如何实现这个功能?
  3. 即使我将请求位置更新的距离提高到100000毫秒和500,有时它仍然每2-5秒运行一次,即使我静止不动!!!我该如何解决这个问题?
非常感谢您的帮助!!!
2个回答

1
您正在请求位置更新,并提供应该在位置更新发生时广播的PendingIntent。然而,您的服务还实现了LocationListener,看起来可能有点混淆。我不确定您在尝试做什么,但首先我建议让您的服务直接获取回调。在这种情况下,您不需要BroadcastReceiver,您应该更改以下内容:
//---request for location updates using GPS---
lm.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, 6000, 5, pendingIntent);

转换为:

//---request for location updates using GPS---
lm.requestLocationUpdates(
    LocationManager.GPS_PROVIDER, 6000, 5, this);

这将导致位置服务定期回调您在服务类中已经实现的方法(onLocationChanged()onProviderEnabled()等)。
此外,您提供的minTime和minDistance参数非常小。 6000的minTime是6秒,minDistance是5米。 这将导致GPS持续开启并耗尽电池,因此您可能需要重新考虑这些参数。
我建议您尝试一下并添加一些日志以查看发生了什么。 我建议使用日志框架(例如:Log.v()Log.e()等),并查看logcat而不是尝试使用toast进行调试。 Toast对于调试来说相当不可靠。
此外,所有设备上的位置服务实现都不同。 每个制造商都提供自己的实现,它们在可靠性,健壮性和操作特性方面差异很大。 没有可靠的方法可以坚持以特定间隔或特定时间获得GPS更新。 您所能做的就是向操作系统提供适当的提示。 无论您指定的参数如何,位置框架都会在需要时回调您。 您只需要理解这一点并相应地编写代码。
如果您想每15分钟更新一次,可以指定15分钟的minTime(即值为15 * 60 * 1000),或者使用闹钟管理器安排一个15分钟的唤醒闹钟,当闹钟响起时,您可以立即请求位置更新(虽然可能需要一些时间才能获取到更新)。希望我提供了足够的材料,让您在这方面取得一些进展。如果需要更多帮助,请随时添加评论。

1

请确保根据您的需求,将以下任一项添加到清单中:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接