我正在制作一个包含 2 个片段的应用程序,它们占据整个屏幕并由一个 viewpager 管理,它们都使用位置数据,我通过实现 LocationManager 来获取位置数据,并使用 LocationListener 检查用户是否移动并需要新数据. 两个片段都使用用户位置来显示初始数据,并且都需要知道用户是否更改了位置以显示新数据。我使用以下代码获取位置数据并请求更新:
private void getLocationData() {
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.d("LOLWeather", "onLocationChange() callback received");
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Log.d("LOLWeather", "onProviderDisabled callback received");
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.ACCESS_COARSE_LOCATION} ,REQUEST_CODE);
return;
}
mLocationManager.requestLocationUpdates(LOCATION_PROVIDER, MIN_TIME, MIN_DISTANCE, mLocationListener);
mLatitude = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER).getLatitude();
mLongitude = mLocationManager.getLastKnownLocation(LOCATION_PROVIDER).getLongitude();
}
我的第一个问题是我想我可以把这段代码放在每个片段中,然后在我可以做的每个片段中 onPause: if(mLocationManager != null) mLocationManager.removeUpdates(mLocationListener);
然而,每次用户从一个片段/视图切换到另一个片段/视图时请求位置数据,并且每次都添加和删除 locationListener 似乎是错误的。由于他们都使用位置数据,我认为最好将 getLocationData() 方法放在活动本身中,这是正确的吗???如果不是我应该如何处理它,将 getLocationData() 方法放在每个片段中???
我的后续问题,除非我错了,这就是我卡住的地方,现在我在主活动中有 getLocationData() 方法,当在 locationListener 中调用 onLocationChanged() 方法时,我如何告诉片段位置已更改,以便它自己更新???我最初通过一个包将数据传递给片段,但是现在创建了片段,我可以在片段中创建一个方法,一旦它有新数据就更新它,但是我如何让它知道它必须更新自己并给出它是新的位置数据???
谢谢。
由于他们都使用位置数据,我认为最好将 getLocationData() 方法放在活动本身中,这是正确的吗???
我认为这是一个很好的方法。
我如何告诉片段位置已更改,以便它自行更新???
您可以在捕获位置更新时发送广播,并将接收器注册到此事件以更新片段。
例如:
当您在活动的方法中捕获更新事件时:
sendBroadcast(new Intent("action_location_updated"));
然后,在您的片段中:
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if ("action_location_updated".equals(intent.getAction())) {
// update fragment here
}
}
};
IntentFilter filter = new IntentFilter("action_location_updated");
registerReceiver(mReceiver, filter);
注意:最好将操作的字符串用作静态最终变量:
public static final ACTION_UPDATE_FRAGMENT = "action_location_updated";
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句