2011-07-20 82 views
0

我有一個服務GPS.java和一個活動message.java綁定到提到的服務(GPS.java)。我使用活頁夾和服務連接限制了他們。我想要使​​用putExtra(Sring,value)發送的我的活動類的值。我將如何接受他們在我的服務?服務和活動

+0

我認爲你必須提供一些示例代碼的SDK的例子你有什麼 –

回答

0

如果您提供的意圖值,當你啓動/綁定到你可以從Intent.getExtras

訪問數據。但是,如果你使用的粘合劑,你需要給了這些服務創建方法的服務價值作爲onBind收到的意圖將不包含任何額外。

下面是一個例子:

在服務:

private final ExampleBinder binder = new ExampleBinder(); 

private class ExampleBinder extends Binder { 
    public void setExtras(Bundle b) { 
     // Set extras and process them 
    } 

    public ExampleService getService() { 
     return ExampleService.this; 
    } 

    public void registerClient(ClientInterface client) { 
     synchronized(clients) { 
      clients.add(client); 
     } 
    } 

    public void unregisterClient(ClientInterface client) { 
     synchronized(clients) { 
      clients.remove(client); 
     } 
    } 
}; 

public IBinder onBind(Intent intent) { 
    return binder; 
} 

private final HashSet<ClientInterface> clients = new HashSet<ClientInterface>(); 

public static interface ClientInterface { 
    int value1(); 
    String value2(); 
} 

在客戶端:

public class ExampleActivity extends Activity implements ExampleService.ClientInterface { 
    private final ServiceConnection connection = new ServiceConnection() { 
     public void onServiceDisconnected(ComponentName name) { 
      // Handle unexpected disconnects (crashes) 
     } 

     public void onServiceConnected(ComponentName name, IBinder service) { 
      ExampleService.ExampleBinder binder = (ExampleService.ExampleBinder) service; 
      binder.registerClient(ExampleActivity.this); 
     } 
    }; 

public void onResume() { 
    bindService(new Intent(this, ExampleService.class), connection, Context.BIND_AUTO_CREATE); 
} 

public void onPause() { 
    unbindService(connection); 
} 

public int value1() { 
    return 4711; 
} 

public String value2() { 
    return "foobar"; 
} 

我可以添加,這是所有假設你不使用AIDL,如果你的解決方案非常相似,只需在你的界面聲明中添加一個額外的方法即可。

你應該閱讀更多關於綁定的服務在這裏:http://developer.android.com/guide/topics/fundamentals/bound-services.html 或看一個例子:http://developer.android.com/reference/android/app/Service.html#LocalServiceSample

還有包含在一個名爲LocationService.java

+0

我認爲Intent.getExtras只能用於onStart()..但我使用的是bindService()。 – SKB

+0

您需要在活頁夾中創建方法,以便在綁定到服務後設置數據。 –

+0

我想從我的服務中的活動中讀取值?有沒有什麼方法可以直接使用R.java文件在活動中讀取這些值?或者請不要讓我看到使用粘合劑的相關代碼? – SKB