2012-11-05 119 views
2

我嘗試爲客戶端和服務器之間的通信創建遠程服務。 的主要思想是啓動服務與我的主要活動 當服務啓動時,它會得到服務器地址和端口來打開一個套接字。android在遠程服務和活動之間進行通信

我希望它是遠程服務,所以其他應用程序將能夠使用相同的服務。 服務將通過從服務器發送和接收數據來保持連接處於活動狀態。 它將有讀\寫Int和String的方法。 換句話說,實現插座的輸入和輸出方法...

我現在面臨的問題是瞭解遠程服務如何在android中工作。 我開始創建一個小服務,只有一個返回int的方法。 這裏是一些代碼:

ConnectionInterface.aidl:

interface ConnectionInterface{ 
     int returnInt(); 
    } 

ConnectionRemoteService.java:

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.os.RemoteException; 
import android.widget.Toast; 

public class ConnectionRemoteService extends Service { 
    int testInt; 

@Override 
public void onCreate() { 
    // TODO Auto-generated method stub 
    super.onCreate(); 
    Toast.makeText(this, "Service created...", Toast.LENGTH_LONG).show(); 
} 



@Override 
public void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show(); 
} 

@Override 
public IBinder onBind(Intent intent) { 
    return myRemoteServiceStub; 
} 

private ConnectionInterface.Stub myRemoteServiceStub = new ConnectionInterface.Stub() { 
    public int returnInt() throws RemoteException { 
     return 0; 
    } 
}; 

}

,並在我的主要活動的 「的onCreate」 部分:

final ServiceConnection conn = new ServiceConnection() { 
     public void onServiceConnected(ComponentName name, IBinder service) { 
      ConnectionInterface myRemoteService = ConnectionInterface.Stub.asInterface(service); 
     } 
     public void onServiceDisconnected(ComponentName name) { 

     } 
    }; 

    final Intent intent = new Intent(this, ConnectionRemoteService.class); 

後來我有一個2個OnClickListeners結合和取消綁定服務:

bindService(intent, conn, Context.BIND_AUTO_CREATE); 
unbindService(conn); 

,我在這裏失蹤,是我如何使用該服務的方法的一個組成部分? 現在我只有1個方法返回一個int值。 我該怎麼稱呼它? 以及我如何使用其他獲取服務值的方法?

謝謝, Lioz。

回答

0

當您成功綁定到該服務時,onServiceConnected()與服務聯編程序一起被調用,然後用於與該服務進行通信。目前你只是把它放在一個局部變量myRemoteService中。你需要做的是將它存儲在主要活動的成員變量中。因此,在您的主要活動定義它是這樣的:

private ConnectionInterface myRemoteService; 

,然後在onServiceConnected()做:

myRemoteService = ConnectionInterface.Stub.asInterface(service); 

以後,當你想使用該服務的方法上,做這樣的事情:

// Access service if we have a connection 
if (myRemoteService != null) { 
    try { 
     // call service to get my integer and log it 
     int foo = myRemoteService.returnInt(); 
     Log.i("MyApp", "Service returned " + foo); 
    } catch (RemoteException e) { 
     // Do something here with the RemoteException if you want to 
    } 
} 

請確保您設置myRemoteService時,你必須服務沒有連接到空。您可以在onServiceDisconnected()中執行此操作。

+0

謝謝,作品很好,很簡單。 – HFDO5

+0

另一件事,如果我添加到清單:android:process =「:remote」,它會讓我的服務在不同的線程中運行嗎?如果沒有,是否有任何簡單的方法可以讓它作爲不同的線程運行?套接字無法在主要活動線程中工作... – HFDO5

+0

如果您使用'android:process =「:remote」'您的服務將運行在另一個**進程**中,而不是另一個線程。在另一個過程中,您仍然必須確保長時間運行的活動不會在主線程中發生。如果您想將網絡活動卸載到單獨的線程中,那麼您需要自己管理它。這並不難。 –

相關問題