2

クライアントとサーバー間で通信するためのリモートサービスを作成しようとしています。主なアイデアは、サービスの開始時に私の主なアクティビティでサービスを開始することです。サーバーのアドレスとポートを取得してソケットを開きます。

他のアプリケーションが同じサービスを使用できるように、リモートサービスにしたいです。このサービスは、サーバーとの間でデータを送受信することにより、接続を維持します。IntとStringの読み取り/書き込みのメソッドがあります。言い換えれば、ソケットの入力と出力のメソッドを実装します。

私が今直面している問題は、Androidでリモートサービスがどのように機能するかを理解することです。私は、intを返すためのメソッドが1つしかない小さなサービスを作成することから始めました。ここにいくつかのコードがあります:

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値を返すメソッドは1つだけです。どうやって呼ぶの?また、サービスに値を取得する他のメソッドをどのように使用しますか?

ありがとう、Lioz。

4

1 に答える 1

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サービスに接続していない場合は、必ずnullに設定してください。あなたはでそれを行うことができますonServiceDisconnected()

于 2012-11-05T14:59:34.553 に答える