Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 当类实现LocationListener时是否调用onLocationChanged?_Android - Fatal编程技术网

Android 当类实现LocationListener时是否调用onLocationChanged?

Android 当类实现LocationListener时是否调用onLocationChanged?,android,Android,我不明白为什么OnLocation在活动中没有调用,而在服务中调用。假设我有一个服务: public class LocationService extends Service implements LocationListener{ @override public void onCreate() { mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE)

我不明白为什么OnLocation在活动中没有调用,而在服务中调用。假设我有一个服务:

public class LocationService extends Service implements LocationListener{

    @override
    public void onCreate() {
    mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
    }

    @Override
    public void onLocationChanged(Location location) { //it is called
        //do something with location 
    }
}
我有一项活动:

public class ViewActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener{
    @Override
    public void onLocationChanged(Location location) { //it is not called
        //do something with location 
    }
}
这是因为我在此活动中没有请求位置更新吗?如果已经在服务中完成了,我为什么要请求它。
另外,我应该如何通过应用程序正确地传播我的位置

如果是在您的服务中完成的,则意味着您需要从活动中启动该服务。如果您使用的活动与您正在使用的活动类似,并且没有位置更新请求,则onLocationChanged将不起作用

这是它实际调用位置更新的部分

requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, this);
我看到您试图在后台使用该服务,并在活动中收到更新。您可能的解决方案是从onLocationChanged方法中的服务发送广播,并在活动中接收广播

因此,从您的服务:

@Override
public void onLocationChanged(Location location) {
    Intent intent = new Intent();
    intent.setAction("com.myapp.LOCATION_CHANGED");
    sendBroadcast(intent);
}
你的活动呢

@Override
public void onReceive(Context context, Intent intent) {
  // do something
}