嗨!我在Mainactivity类中有一个locationlistener和manager,但我认为这是一个非常糟糕的解决方案,因为我希望在不同的类中使用location functionallity,因为我希望监听器能够持续使用Intents。
我只有大约10个小时的Android编程经验,所以这对某些人来说可能看起来很糟糕;)
主要活动
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_xxx);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
location = new RetrieveLocation(this);
checkForPermission();
...
//I want this method to call location.getCoordinates() in 1 second intervals
public void updateMap() {
if (location.hasFoundLocation()) {
enableButton();
marker.setPosition(location.getCoordinates());
map.animateCamera(CameraUpdateFactory.newLatLngZoom(location.getCoordinates(), 16));
}
else {
disableButton();
}
}
public void checkForPermission()
{
if (Build.VERSION.SDK_INT >= 23) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION
}, 10);
}
else {
location.listen();
updateMap();
}
}
因此,retrieveLocation类基本上只是在移动设备时更新用户位置。
所以我想每秒抓住mainActivity类的坐标并更新标记谷歌地图。
RetrieveLocation
public class RetrieveLocation
{
private LocationManager locationManager;
private LocationListener locationListener;
private LatLng _location;
private Context context;
public RetrieveLocation(Context context)
{
this.context = context;
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
public void listen()
{
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
_location = new LatLng(location.getLatitude(), location.getLongitude());
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
};
//noinspection ResourceType
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0, 0, locationListener);
}
...
public LatLng getCoordinates()
{
if(_location != null)
return _location;
else
return new LatLng(0,0);
}
在写这篇文章
之前,我已经搜索了很多答案 0 :(得分:0)
如果您希望您的监听器持续使用意图,您应该从服务中调用它并从那里订阅事件。在收到活动时,您还必须更新您的用户界面。