2

我尝试为客户端和服务器之间的通信创建远程服务。主要思想是用我的主要活动启动服务,当服务启动时,它将获取服务器地址和端口以打开套接字。

我希望它是远程服务,以便其他应用程序能够使用相同的服务。该服务将通过向服务器发送和接收数据来保持连接处于活动状态。它将具有读取\写入 Int 和 String 的方法。换句话说,实现套接字输入和输出方法......

我现在面临的问题是了解远程服务在 android 中是如何工作的。我从创建一个小型服务开始,它只有一种返回 int 的方法。这是一些代码:

连接接口.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 值的方法。我怎么称呼它?以及如何使用其他方法为服务获取值?

谢谢,利奥兹。

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 回答