Я пытаюсь запустить службу переднего плана Android для подключения в режиме реального времени к моему серверу с помощью собственного клиента Android Socket-IO, и он работает, когда я запускаю приложение в режиме отладки, но когда я запускаю его с в режиме выпуска выполняется только событие подключения, а другие события работать не будут
Service.kt
class MyService() : Service() {
private val notifBuilder = NotificationCompat.Builder(this, ongoingChannelId)
.setSmallIcon(R.drawable.ic_notification_offline)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setOngoing(true)
override fun onCreate() {
Log.e(TAG, "onCreate: Service ONCREATE")
notificationIntent = Intent(this, MainActivity::class.java)
pendingIntent = PendingIntent.getActivity(
applicationContext,
0, notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
notifBuilder.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setContentTitle(getString(R.string.app_name))
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand: ")
createNotificationChannel()
startForeground(onGoingNotificationId, notifBuilder.build())
startSocket()
return START_STICKY
}
private fun startSocket() {
if (!socketStarted) {
socketStarted = true
socket.on(Socket.EVENT_CONNECT) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_CONNECT}")
notifBuilder.setContentText("Connected to Server")
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
socket.emit(
SOCKET_EVENT_LOGIN,
"my token"
)
if (this::pingTimerTask.isInitialized)
pingTimerTask.cancel()
pingTimerTask = object : TimerTask() {
override fun run() {
Log.e(TAG, "run: Pinging ".plus(socket.connected()))
if (socket.connected())
socket.emit(
SOCKET_EVENT_PING,
"my token"
)
}
}
pingTimer = if (!this::pingTimer.isInitialized)
Timer(true)
else {
pingTimer.cancel()
pingTimer.purge()
Timer(true)
}
pingTimer.schedule(pingTimerTask, 2000, 10000)
}
socket.on(Socket.EVENT_CONNECT_ERROR) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_CONNECT_ERROR}")
notifBuilder.setContentText("Connection error to Server")
.setSmallIcon(R.drawable.ic_notification_offline)
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
pingTimer.cancel()
}
socket.on(Socket.EVENT_DISCONNECT) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_DISCONNECT}")
notifBuilder.setContentText("Disconnected from Server")
notifBuilder.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification_offline)
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
pingTimer.cancel()
}
socket.on(SOCKET_EVENT_ONLINE, loginListener)
socket.connect()
}
}
@SuppressLint("MissingPermission")
private val loginListener = Emitter.Listener { res ->
Log.e(TAG, "loginListener: Pinged")
val date = System.currentTimeMillis()
val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
val dateStr: String = dateFormat.format(date)
notifBuilder.setContentText("Last Ping was $dateStr")
.setSmallIcon(R.drawable.ic_notification_online)
NotificationManagerCompat.from(this).notify(onGoingNotificationId, notifBuilder.build())
}
}
Поэтому я ожидаю получить событие входа в систему каждый раз, когда я пингую сервер
и запускаю службу следующим образом
serviceIntent = Intent(requireContext(), MyService::class.java)
ContextCompat.startForegroundService(requireContext(),serviceIntent)
Подробнее здесь: https://stackoverflow.com/questions/772 ... rd-enabled
Socket-io Android не работает с включенной защитой pro-guard ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1728553893
Anonymous
Я пытаюсь запустить службу переднего плана Android для подключения в режиме реального времени к моему серверу с помощью собственного клиента Android Socket-IO, и [b]он работает, когда я запускаю приложение в режиме отладки[/b], но когда я запускаю его с [b]в режиме выпуска выполняется только событие подключения[/b], а другие события работать не будут
Service.kt
class MyService() : Service() {
private val notifBuilder = NotificationCompat.Builder(this, ongoingChannelId)
.setSmallIcon(R.drawable.ic_notification_offline)
.setPriority(NotificationCompat.PRIORITY_MIN)
.setOngoing(true)
override fun onCreate() {
Log.e(TAG, "onCreate: Service ONCREATE")
notificationIntent = Intent(this, MainActivity::class.java)
pendingIntent = PendingIntent.getActivity(
applicationContext,
0, notificationIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_MUTABLE
)
notifBuilder.setContentIntent(pendingIntent)
.setOnlyAlertOnce(true)
.setContentTitle(getString(R.string.app_name))
super.onCreate()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.e(TAG, "onStartCommand: ")
createNotificationChannel()
startForeground(onGoingNotificationId, notifBuilder.build())
startSocket()
return START_STICKY
}
private fun startSocket() {
if (!socketStarted) {
socketStarted = true
socket.on(Socket.EVENT_CONNECT) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_CONNECT}")
notifBuilder.setContentText("Connected to Server")
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
socket.emit(
SOCKET_EVENT_LOGIN,
"my token"
)
if (this::pingTimerTask.isInitialized)
pingTimerTask.cancel()
pingTimerTask = object : TimerTask() {
override fun run() {
Log.e(TAG, "run: Pinging ".plus(socket.connected()))
if (socket.connected())
socket.emit(
SOCKET_EVENT_PING,
"my token"
)
}
}
pingTimer = if (!this::pingTimer.isInitialized)
Timer(true)
else {
pingTimer.cancel()
pingTimer.purge()
Timer(true)
}
pingTimer.schedule(pingTimerTask, 2000, 10000)
}
socket.on(Socket.EVENT_CONNECT_ERROR) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_CONNECT_ERROR}")
notifBuilder.setContentText("Connection error to Server")
.setSmallIcon(R.drawable.ic_notification_offline)
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
pingTimer.cancel()
}
socket.on(Socket.EVENT_DISCONNECT) {
Log.e(TAG, "onStartCommand: ${Socket.EVENT_DISCONNECT}")
notifBuilder.setContentText("Disconnected from Server")
notifBuilder.setOngoing(false)
.setSmallIcon(R.drawable.ic_notification_offline)
NotificationManagerCompat.from(this)
.notify(onGoingNotificationId, notifBuilder.build())
pingTimer.cancel()
}
socket.on(SOCKET_EVENT_ONLINE, loginListener)
socket.connect()
}
}
@SuppressLint("MissingPermission")
private val loginListener = Emitter.Listener { res ->
Log.e(TAG, "loginListener: Pinged")
val date = System.currentTimeMillis()
val dateFormat = SimpleDateFormat("HH:mm:ss", Locale.getDefault())
val dateStr: String = dateFormat.format(date)
notifBuilder.setContentText("Last Ping was $dateStr")
.setSmallIcon(R.drawable.ic_notification_online)
NotificationManagerCompat.from(this).notify(onGoingNotificationId, notifBuilder.build())
}
}
Поэтому я ожидаю получить событие входа в систему каждый раз, когда я пингую сервер
и запускаю службу следующим образом
serviceIntent = Intent(requireContext(), MyService::class.java)
ContextCompat.startForegroundService(requireContext(),serviceIntent)
Подробнее здесь: [url]https://stackoverflow.com/questions/77272835/socket-io-android-doesnt-work-with-pro-guard-enabled[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия