从活动中的服务类访问套接字连接

时间:2017-07-12 14:49:04

标签: java android sockets broadcastreceiver android-service

我正在尝试从我的活动类中的服务类访问套接字连接,并在线emit将数据发送到我的服务器。

    MyService.java

    public class MyService extends Service {

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

        @Override
        public void onCreate() {
            this.isRunning = false;
            this.backgroundThread = new Thread(myTask);
        }

        private Runnable myTask = new Runnable() {
            @Override
            public void run() {


                try {
                    // instantiate socket connection
                    mSocket = IO.socket(AppConstants.CHAT_SERVER_URL);

                    // establish the socket connection
                    mSocket.connect();

                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
            }
        };

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            if( !this.isRunning) {
                this.isRunning = true;
                this.backgroundThread.start();
            }

            return START_STICKY;
        }

        public Socket getSocket() {
            return mSocket;
        }
    }



    MyApplication.java

    public class MyApplication extends Application {

        @Override
        public void onCreate() {
            super.onCreate();

            Intent background = new Intent(this, MyService.class);
            startService(background);
        }
    }


    MainActivity.java

    public class MainActivity extends Activity {


        Socket mSocket;
        MyService mservice;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            mSocket = mservice.getSocket();

        }

        public void sendMessage(View view){
            mSocket.emit("new messaged", "this");
        }

    }

当触发sendMessage中的MainActivity方法时,即使连接在启动时建立,上面也会出现空错误。

我非常了解,我可以bind连接并使用活动类中的ServiceConnection类来访问mSocket连接,但是我要使用这种方式或{ {1}}访问它。关于最好的访问套接字连接而不将服务类绑定到活动类的任何想法。

1 个答案:

答案 0 :(得分:0)

你应该得到一个NullPointerException

mSocket = mservice.getSocket();

因为你永远不会将mservice分配给任何东西!