2012-11-05 213 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”'您的服务将运行在另一个**进程**中,而不是另一个线程。在另一个过程中,您仍然必须确保长时间运行的活动不会在主线程中发生。如果您想将网络活动卸载到单独的线程中,那么您需要自己管理它。这并不难。 –

相关问题