【发布时间】:2014-03-28 22:06:14
【问题描述】:
我正在尝试使用 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 服务和统一的第一步,但我还没有找到解决方案。 非常感谢任何建议,或者如果您知道另一种从建立套接字连接的 android 服务向统一发送数据的方法,那就太好了! 感谢您的帮助!
【问题讨论】:
标签: java android sockets unity3d