2011-07-15 145 views
1

我有一個名爲message.java的活動,它綁定到服務GPS.java。必須在message.java中使用從GPS.java獲取的經度和緯度。我們通過使用servicebinder在onServiceConnected()中獲取緯度和經度的默認值。 這裏是message.java如何通知服務完成活動?

`Intent i=new Intent(getApplicationContext(), GPS.class); 
      bindService(i,mConnection,Context.BIND_AUTO_CREATE) 




     private GPS servicebinder; 
     ServiceConnection mConnection = new ServiceConnection() { 
      public void onServiceConnected(ComponentName className, IBinder service) { 
       servicebinder = ((GPS.MyBinder)service).getService(); 

       double lat=servicebinder.getlatitude(); 

       double lon=servicebinder.getlongitude(); 
        tex.setText("\nlatitude: " + lat+ "\nlongitude: " 
         + lon); 


       // do any extra setup that requires your Service 
       } 

getLatitude()和getLongitude()返回的緯度和經度在GPS.java發現這是正確的代碼。問題是上面顯示的緯度和經度打印默認值,所以當服務的經度和經度更新時,我希望緯度和經度也應該更新(活動應通知服務更新)

請給該代碼將它們放置適當

回答

0

首先創建一個類似MyLocationListener接口如下

public interface MyLocationListener { 
    public void locationChanged(double lat, double lon); 
} 

現在更新GPS類作爲

public class GPS { 
    ArrayList<MyLocationListener> listeners = new ArrayList<MyLocationListener>(); 

    public void addLocationListener(MyLocationListener listener) { 
    listeners.add(listener); 
    } 
} 

那麼,你已經改變了經緯度只是調用

notifyChangeLocation(lat, lon); 

而且這種方法有以下代碼:

public void notifyChangeLocation(double lat, double lon) { 
Iterator<MyLocationListener> itr = listeners.iterator(); 
    while(itr.hasNext()) { 
    itr.next().locationChanged(lat, lon); 
    } 
} 

這是第一部分,現在的第二件事是添加聽衆在您的活動,通過做一個類MyServiceConnection這是這樣的:

public class MyServiceConnection implements ServiceConnection, MyLocationListener { 
    //add the unimplemented methods 
    public void locationChanged(double lat, double lon) { 
    // do any extra setup that requires your Service 
    } 
} 
ServiceConnection mConnection = new MyServiceConnection(); 
Intent i=new Intent(getApplicationContext(), GPS.class); 
bindService(i,mConnection,Context.BIND_AUTO_CREATE); 

現在只需註冊監聽呃 gps.addLocationListener(mConnection);