[英]Android. Use service or application class for locationListener
我有一項確定用戶位置的任務。 我可以在Application類中創建LocationListener。 或者我可以使用服務。
LocationManager locationManager=(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener=new LocationListener(){
public void onLocationChanged( Location location){
dive.setLongitude(location.getLongitude());
dive.setLatitude(location.getLatitude());
mapHelper.setMapPosition(dive.getLatitude(),dive.getLongitude());
}
public void onStatusChanged( String provider, int status, Bundle extras){
}
public void onProviderEnabled( String provider){
}
public void onProviderDisabled( String provider){
}};
locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,0,0,locationListener);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER,0,0,locationListener);
我需要為該任務使用什么? 服務或應用程序類? 服務的優缺點是什么? 應用程序類的優缺點是什么?
您永遠都不會使用該應用程序。 您可以使用活動。 使用“活動”更為方便,但不能繼續進行下一個活動。 服務需要額外的樣板,並且不太容易訪問數據,但是可以用於需要數據的多個活動。
如果您的應用程序需要獲取實時位置信息,則可以同時使用兩者。
MyApplication extends Application implements locationListener
MyService extends Service implements locationListener
因為應用程序的生命周期最長,所以您可以在服務中使用該應用程序。您只需要擔心如何將獲取的數據傳遞給Activity(接口,廣播...)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.