Android-Unity服务NetworkOnMainThreadException

时间:2014-03-28 13:45:26

标签: java android sockets unity3d

我尝试使用Android提供的服务向Unity发送数据,我一直在关注tutorial这样做并且运行正常但是我需要创建套接字连接到从服务器接收数据,然后将其作为广播消息发送,就像教程显示的那样。问题是,由于套接字连接,我在启动应用程序时得到NetworkOnMainThreadException。我已经看到使用AsyncTask可以解决问题,但我仍然不知道如何实现服务并以这种方式发送广播消息。

这是服务代码:

private final Handler handler = new Handler();


// It's the code we want our Handler to execute to send data
private Runnable sendData = new Runnable() {
        // the specific method which will be executed by the handler
        public void run() {

                Socket socket = null;

                try{

                    socket = new Socket("x.x.x.x", 1337);

                    BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));

                    String line ="";

                    line = input.readLine();                    

                    numIntent++;

                    // sendIntent is the object that will be broadcast outside our app
                    Intent sendIntent = new Intent();

                    // We add flags for example to work from background                    
                    sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES  );

                    // SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen.
                    // By convention, it's suggested to use the current package name
                    sendIntent.setAction("com.test.service.IntentToUnity");

                    // Here we fill the Intent with our data, here just a string with an incremented number in it.
                    //sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent);
                    sendIntent.putExtra(Intent.EXTRA_TEXT, line);
                    // And here it goes ! our message is send to any other app that want to listen to it.
                    sendBroadcast(sendIntent);

                    // In our case we run this method each second with postDelayed
                    handler.removeCallbacks(this);
                    handler.postDelayed(this, 1000);

                }catch(IOException e){
                    e.printStackTrace();

                }
        }
};

// When service is started
@Override
public void onStart(Intent intent, int startid) {
        // We first start the Handler
        handler.removeCallbacks(sendData);
        handler.postDelayed(sendData, 1000);
}

我不确定这是一个简单的问题,因为这些是我服务和统一的第一步,但我还没有找到解决方法。 任何建议都很受欢迎,或者你知道另一种方法从一个Android服务发送数据到统一,其中一个套接字连接将是伟大的! 谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

Service切换到IntentService,应解决问题。 IntentService在单独的线程上运行,而Service在UI线程上运行