【发布时间】:2017-08-13 04:03:19
【问题描述】:
我在 Android 中使用 socket.io。我在 node.js 服务器中成功连接了我的 android 应用程序。一切都很完美,但我尝试在 Sturtup 上创建连接,但套接字自动断开 这是我的来源
public class AutoRunService extends BroadcastReceiver {
private static Socket socket;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(UApplication.getInstance(), "Application is ready to open ", Toast.LENGTH_SHORT).show();
seSocketConnection(context);
}
}
public void seSocketConnection(final Context context) {
try {
socket = IO.socket("http://192.168.101.139:8080");
socket.on("onconnect", new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject obj = new JSONObject();
Log.e("AutoRunService", "onconnect");
try {
obj.put("host", "************");
obj.put("entity", new DeviceManager(UApplication.getInstance()).getDeviceId());
socket.emit("initialize", obj);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).on("onerror", new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.e("AutoRunService", "onerror");
}
}
).on("device", new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.e("AutoRunService", "device");
Intent i = new Intent(context, WelcomeImageActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
).on(Socket.EVENT_CONNECT_ERROR, new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.e("AutoRunService", "EVENT_CONNECT_ERROR");
}
}).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
// socket.disconnect();
Log.e("AutoRunService", "EVENT_DISCONNECT");
}
});
socket.connect();
} catch (URISyntaxException e) {
e.printStackTrace();
Log.e("AutoRunService", e.toString());
}
}
}
清单源代码
<receiver
android:name=".AutoRunService"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
当然,我在清单中有 Internet 连接权限。我不知道我的来源有什么问题。正如我所说的套接字连接在 Activity 中工作完美 我怎样才能解决我的问题? 谢谢
【问题讨论】:
标签: android node.js sockets socket.io