2011-09-16 89 views
2

我正在處理示例應用程序。在此應用程序中,我想獲得更新的位置緯度和經度,當用戶移動的Android移動的方式。我有實現定位管理類,如下所示:如何獲取位置的經緯度和從後臺服務更新

private LocationManager locationManager; 
private LocationListener locationListener; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);  

    locationListener = new GPSLocationListener(); 

    locationManager.requestLocationUpdates(
     LocationManager.GPS_PROVIDER, 
     0, 
     0, 
     locationListener); 
    } 

     private class GPSLocationListener implements LocationListener 
{ 
    @Override 
    public void onLocationChanged(Location location) { 
     if (location != null) { 
     Toast.makeText(getBaseContext(), 
        "Latitude: " + location.getLatitude() + 
        " Longitude: " + location.getLongitude(), 
        Toast.LENGTH_SHORT).show(); 
      } 
     } 

}

如何獲得更新從回地面位置的緯度和經度?

請任何機構幫助我。

回答

2

如果您打算在應用程序未運行時獲取經度和緯度,則可以使用Service獲取背景中的經度和緯度,並執行您想要的任何任務。另外,不要忘記在不需要時刪除更新,因爲獲取更新在設備電池使用方面成本非常高。

還有一件事,你不需要檢查空值的位置,因爲onLocationChanged()只會在你的提供者獲得一個位置時被調用。

雖然我也是android的新手。這可能會幫助你。你必須看到android文檔這些Service類方法實際上做了什麼以及什麼時候被調用。 這是未完成的代碼。你已經在這裏自己實現了locationlistener。這只是一個示例程序,它顯示了一個普通的類:

import java.util.Timer; 
import java.util.TimerTask; 
import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 

public class BackService extends Service { 

private MyTimerTask mTimerTask; 
private Timer mTimer; 

@Override 
public void onCreate() { 
    mTimer = new Timer(); 
    mTimerTask = new MyTimerTask(); 
} 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    mTimer.schedule(mTimerTask, 0, 500); 
    Log.d("onStartCommand","onStartCommand called..."); 
    return START_STICKY; 
} 

@Override 
public IBinder onBind(Intent intent) { 
    // TODO Auto-generated method stub 
    return null; 
} 

private class MyTimerTask extends TimerTask { 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     Log.i("BackService","BackService is running..."); 
     doSomethingWithLocation(); 
    } 

} 


} 
+0

ü可以plzzz給出任何示例代碼上it.bcz我是在它新 –

相關問題