对于TCP套接字的Andr​​oid服务 [英] Android service for TCP Sockets

查看:197
本文介绍了对于TCP套接字的Andr​​oid服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于在previous问题,我问在这里建议

,我试图把我的,我已经写进服务的应用程序套接字连接。我花了一天的大部分时间昨天研究服务,实际上嘲笑了一些(一个遥控器,一个本地)。

我的问题是两部分:

1),有玩既具有本地服务和远程服务后,我真不知道是哪一个将是最适合我的情况。这是由于在很大程度上是这一事实,我想我还是不太明白在另一个'过程'运行的优点是要给我的。我生成一个新的线程套接字连接不管是什么,所以我不会有任何线程争与UI。那么,是什么把服务于另一个进程让我做什么?请问我可能看到更好的表现呀?我有限的理解是,通过将它放在一个不同的过程中,该服务将独立于​​任何活动我在我的应用程序已经运行的运行。我确实有一些不同的活动,但只有其中一人需要套接字连接,我会重建每次的活动反正打开。因此,将本地服务是要走的路我?

2)我将有我的插座监听器​​(的DataInputStream()。的readLine()在while循环中)在我服务的那个东西从服务器传下来的任何新数据。播放昨天我做了之后,我无法弄清楚如何通过它读取到实际的客户(通过远程服务,或本地客户端本身绑定的客户端)的实时的数据。

将大大AP preciate一些建议第1部分,和一些帮助与第2部分(code的例子:?))

TIA

编辑:加入我的服务的code - 与当地的服务去

服务类:

 公共类SocketService延伸服务{

    插座S;
    PrintStream的操作系统;

    @覆盖
    公众的IBinder onBind(意向为arg0){
        // TODO自动生成方法存根
        返回myBinder;
    }

    私人最终的IBinder myBinder =新LocalBinder();

    公共类LocalBinder扩展粘合剂{
        公共SocketService的getService(){
            返回SocketService.this;
        }
    }


    @覆盖
    公共无效的onCreate(){
        super.onCreate();
        S =新的Socket();
    }

    公共无效IsBoundable(){
        Toast.makeText(这一点,我绑定如黄油,Toast.LENGTH_LONG).show();
    }

    公共无效ONSTART(意向意图,诠释startId){
        super.onStart(意向,startId);
        Toast.makeText(本,服务创造......,Toast.LENGTH_LONG).show();
        Runnable接口连接=新connectSocket();
        新的线程(连接)。启动();
    }

    类connectSocket实现Runnable {

        @覆盖
        公共无效的run(){
            SocketAddress的SocketAddress的=新的InetSocketAddress(192.168.1.104,4505);
            尝试 {
                s.connect(SocketAddress的);
            }赶上(IOException异常E){
                e.printStackTrace();
            }

        }

    }

    @覆盖
    公共无效的onDestroy(){
        super.onDestroy();
        尝试 {
            S.CLOSE();
        }赶上(IOException异常E){
            // TODO自动生成的catch块
            e.printStackTrace();
        }
        S = NULL;
    }
}
 

活动调用的服务:

 公共类SocketServiceController延伸活动{

        私人SocketService mBoundService;
        私人布尔mIsBound;
        公共SocketServiceController SSC;
       @覆盖
        保护无效的onCreate(包savedInstanceState){
            super.onCreate(savedInstanceState);
            SSC =这一点;
            的setContentView(R.layout.main);

            按钮启动=(按钮)findViewById(R.id.serviceButton);
            按钮停止=(按钮)findViewById(R.id.cancelButton);

            start.setOnClickListener(startListener);
            stop.setOnClickListener(stopListener);

       }

       私人ServiceConnection mConnection =新ServiceConnection(){
            公共无效onServiceConnected(组件名的className,服务的IBinder){
                mBoundService =((SocketService.LocalBinder)服务).getService();

            }
            公共无效onServiceDisconnected(组件名的className){
                mBoundService = NULL;
            }
        };

        私人无效doBindService(){
            bindService(新意图(SocketServiceController.this,SocketService.class),mConnection,Context.BIND_AUTO_CREATE);
            mIsBound = TRUE;
            mBoundService.IsBoundable();
        }


        私人无效doUnbindService(){
            如果(mIsBound){
                //分离我们的现有连接。
                unbindService(mConnection);
                mIsBound = FALSE;
            }
        }

        @覆盖
        保护无效的onDestroy(){
            super.onDestroy();
            doUnbindService();
        }


       私人OnClickListener startListener =新OnClickListener(){
        公共无效的onClick(视图v){
            startService(新意图(SocketServiceController.this,SocketService.class));
            doBindService();

        }
       };

       私人OnClickListener stopListener =新OnClickListener(){
            公共无效的onClick(视图v){
                stopService(新意图(SocketServiceController.this,SocketService.class));
            }
          };
}
 

解决方案
  

这是由于在很大程度上是这一事实,我想我还是不太明白在运行的优点   另一种过程是要给我的。

一般情况下,没有。您创建一个远程服务,如果你期待其他应用程序与服务进行通信。如果它只会使用自己的应用程序,使用本地服务。

此外,远程服务无关,与你的应用程序中创建一个单独的进程。

  

我会潜在地看到更好的表现呀?

您会看到更糟糕的表现那样,由于额外的内存消耗。

  

我有限的了解是,通过将它放在一个不同的进程,该服务将独立运行   什么活动我在我的应用程序都运行。

服务具有独立于活动的一个生命周期,无论是本地还是远程的。

  

于是将本地服务是要走的路我?

听起来可能。

  

播放我没有昨天,我无法弄清楚如何通过它读取到数据后   实际的客户(或者绑定的客户端通过远程服务或本地客户端本身)的实时。

使用的本地绑定模式,并具有活性调用API的服务注册(和注销)事件侦听器。具有服务经由听者传递数据到活动

Based on a suggestion in a previous question I asked on here, I'm trying to push my socket connection for an application that I've written into a service. I spent the better part of the day yesterday researching services and actually mocked up a few (one remote, one local).

My question is in two parts:

1) after having played with both a local service and a remote service, I'm still not sure as to which one would be best for my situation. This is due in large part to the fact that I guess I still don't quite understand what advantages running in another 'process' is going to give me. I'm spawning a new thread for the socket connection no matter what so I won't have any thread contention with the UI. So what does putting the service in another process enable me to do? Will I potentially see better performance that way? My limited understanding is that by putting it in a different process, the service will run independently of whatever activity I have running on my app. I do have a few different activities, but only one of them requires the socket connection which I will rebuild everytime that activity is opened anyway. So would a local service be the way to go for me?

2) I'm going to have my socket "listener" (DataInputStream().readLine() inside a while loop) inside my service for any new data that gets passed down from the server. After the playing I did yesterday, I could not figure out how to pass the data that it reads to the actual "client" (either bound client by remote service, or local client itself) in "realtime".

Would greatly appreciate some suggestions for part 1, and some help with part 2 (code examples? :))

TIA

Edit: added code of my service - going with local service

Service Class:

   public class SocketService extends Service {

    Socket s;
    PrintStream os;

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return myBinder;
    }

    private final IBinder myBinder = new LocalBinder();

    public class LocalBinder extends Binder {
        public SocketService getService() {
            return SocketService.this;
        }
    }


    @Override
    public void onCreate() {
        super.onCreate();
        s = new Socket();
    }

    public void IsBoundable(){
        Toast.makeText(this,"I bind like butter", Toast.LENGTH_LONG).show();
    }

    public void onStart(Intent intent, int startId){
        super.onStart(intent, startId);
        Toast.makeText(this,"Service created ...", Toast.LENGTH_LONG).show();
        Runnable connect = new connectSocket();
        new Thread(connect).start();
    }

    class connectSocket implements Runnable {

        @Override
        public void run() {
            SocketAddress socketAddress = new InetSocketAddress("192.168.1.104", 4505);
            try {               
                s.connect(socketAddress);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            s.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        s = null;
    }
}

Activity that calls service:

public class SocketServiceController extends Activity {

        private SocketService mBoundService;
        private Boolean mIsBound;
        public SocketServiceController ssc;
       @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            ssc = this;
            setContentView(R.layout.main);

            Button start = (Button)findViewById(R.id.serviceButton);
            Button stop = (Button)findViewById(R.id.cancelButton);

            start.setOnClickListener(startListener);
            stop.setOnClickListener(stopListener);

       }

       private ServiceConnection mConnection = new ServiceConnection() {
            public void onServiceConnected(ComponentName className, IBinder service) {
                mBoundService = ((SocketService.LocalBinder)service).getService();

            }
            public void onServiceDisconnected(ComponentName className) {
                mBoundService = null;
            }
        };

        private void doBindService() {
            bindService(new Intent(SocketServiceController.this, SocketService.class), mConnection, Context.BIND_AUTO_CREATE);
            mIsBound = true;
            mBoundService.IsBoundable();
        }


        private void doUnbindService() {
            if (mIsBound) {
                // Detach our existing connection.
                unbindService(mConnection);
                mIsBound = false;
            }
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            doUnbindService();
        }


       private OnClickListener startListener = new OnClickListener() {
        public void onClick(View v){
            startService(new Intent(SocketServiceController.this,SocketService.class));
            doBindService(); 

        }               
       };

       private OnClickListener stopListener = new OnClickListener() {
            public void onClick(View v){
                stopService(new Intent(SocketServiceController.this,SocketService.class));
            }               
          };
}

解决方案

This is due in large part to the fact that I guess I still don't quite understand what advantages running in another 'process' is going to give me.

Generally, none. You create a remote service if you are expecting other applications to communicate with the service. If it will only be used by your own application, use a local service.

Also, a remote service has nothing to do with creating a separate process within your application.

Will I potentially see better performance that way?

You will see worse performance that way, due to extra memory consumption.

My limited understanding is that by putting it in a different process, the service will run independently of whatever activity I have running on my app.

Services have a lifecycle independent from activities regardless of whether it is local or remote.

So would a local service be the way to go for me?

Sounds likely.

After the playing I did yesterday, I could not figure out how to pass the data that it reads to the actual "client" (either bound client by remote service, or local client itself) in "realtime".

Use the local binding pattern, and have the activity call an API on the service to register (and unregister) an event listener. Have the service pass the data to the activity via the listener.

这篇关于对于TCP套接字的Andr​​oid服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆