2013-03-20 64 views
0

我目前正在写一个应用程序,应执行以下操作:为服务GPS追踪器

  • 的UI只包含一个切换按钮。如果打开,GPS位置应发送到外部服务器。如果关闭,则不会发生任何事情。

  • 如果按钮已打开且应用程序(活动)已关闭,则仍应发送该位置,直到该按钮再次关闭。

我该如何做到这一点?我阅读了大量的线程和教程,并在dev.google.com上,但我无法找到解决问题的最佳解决方案。

我目前的做法:

MainActivity.java

public void onClick(View v) { 
    if (onOffButton.isChecked()) { 
     Intent startIntent = new Intent(this, LocationService.class); 
     startService(startIntent); 
    } else { 
     stopService(new Intent(this, LocationService.class)); 
    } 
} 

LocationService.java

public class LocationService extends Service implements LocationListener { 

     final public static String START_ACTION = "START_LOCATION"; 
     final public static int NOTE_ID = 1; 

     private int updateRate; 

     private LocationManager locationManager; 
     private NotificationManager notifyManager; 

     @Override 
     public IBinder onBind(Intent arg0) { 
       return null; 
     } 

     @Override 
     public void onStart(Intent intent, int startId) { 
       super.onStart(intent, startId); 

       // show popup message 
       Toast.makeText(this, getText(R.string.start_message), Toast.LENGTH_SHORT).show(); 

       // display icon in status bar 

       requestLocationUpdates(); 
     } 

     private void requestLocationUpdates() { 
       if(locationManager != null) 
         locationManager.removeUpdates(this); 

       // get location service 
       Criteria crit = new Criteria(); 
       crit.setPowerRequirement(Criteria.ACCURACY_FINE); 
       String bestProvider = getLocationManager().getBestProvider(crit, true); 
       getLocationManager().requestLocationUpdates(bestProvider, updateRate * 1000, 
           0 /* minDist */, this); 

       LocationService.running = true; 
     } 

     @Override 
     public void onDestroy() { 
       super.onDestroy(); 
       getLocationManager().removeUpdates(this); 
       notifyManager.cancel(NOTE_ID); 
       Toast.makeText(this, getText(R.string.stop_message), Toast.LENGTH_SHORT).show(); 
       LocationService.running = false; 
     } 

     @Override 
     public void onLocationChanged(Location location) { 
       //Send Location to Server 
     } 

     @Override 
     public void onProviderDisabled(String provider) { 
       // TODO stop service, notify user 
     } 

     @Override 
     public void onProviderEnabled(String provider) { 
       requestLocationUpdates(); 
     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
       // TODO notify user 
     } 

     private LocationManager getLocationManager() { 
       if (this.locationManager == null) 
         this.locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
       return this.locationManager; 
     } 
} 

我得到这个从一个很旧的GPS追踪我在互联网上找到(我知道onStart()已被弃用,应该替换为onCommandStart())I只是想知道如果一般的做法是好的..

问候。

回答

0

该方法看起来不错。您只需要实施回拨方法来报告您的位置。