package com.example.flutter_application_1
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Handler
import android.os.IBinder
import androidx.core.app.NotificationCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
class BackgroundService : Service() {
private val mHandler: Handler = Handler()
private val mRunnable: Runnable = object : Runnable {
override fun run() {
checkURL("http://URL")
mHandler.postDelayed(this, 1000) // Run every 1 second
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
startForegroundService()
mHandler.post(mRunnable)
return START_STICKY
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
private fun checkURL(url: String) {
GlobalScope.launch(Dispatchers.IO) {
val client = OkHttpClient()
val request = Request.Builder()
.url(url)
.build()
try {
client.newCall(request).execute().use { response ->
if (response.isSuccessful) {
val content = response.body?.string() ?: ""
sendNotification("URL Response", content)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
}
}
private fun sendNotification(title: String, message: String) {
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationId = 1
val channelId = "background_service_channel"
val channelName = "Background Service Channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
channel.lightColor = Color.BLUE
channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
notificationManager.createNotificationChannel(channel)
}
val intent = Intent(this, MainActivity::class.java)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(R.drawable.ic_notification)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
notificationManager.notify(notificationId, notificationBuilder.build())
}
private fun startForegroundService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channelId = "background_service_channel"
val channelName = "Background Service Channel"
val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val notification = createNotification()
startForeground(NOTIFICATION_ID, notification)
}
private fun createNotification(): Notification {
val channelId = "background_service_channel"
val notificationBuilder = NotificationCompat.Builder(this, channelId)
.setContentTitle("Foreground Service")
.setContentText("Running...")
.setSmallIcon(R.drawable.ic_notification)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
return notificationBuilder.build()
}
companion object {
private const val NOTIFICATION_ID = 12345678
}
}
Мне не удалось ничего найти в сети, поэтому надеюсь, что если я получу ответ, это принесет пользу и другим.
Это преследуемая проблема, которая не дает мне спать.
Я хочу создать фоновую службу для проверки URL-адреса и отправки уведомления пользователю, если код состояния равен 200. У меня есть две проблемы:[list] [*]Раздражающее уведомление для службы переднего плана (если я его не отправлю, моя служба не будет работать, когда пользователь закроет приложение) [*]Я хочу иметь возможность передавать URL-адрес из файла dart в мой файл kt. [/list] Вот код: [b]Main.dart[/b] [code]import 'package:flutter/material.dart'; import 'package:flutter/services.dart';
void main() { runApp(MyApp()); }
class MyApp extends StatelessWidget { static const platform = MethodChannel('com.example.background_service');
class BackgroundService : Service() { private val mHandler: Handler = Handler() private val mRunnable: Runnable = object : Runnable { override fun run() { checkURL("http://URL") mHandler.postDelayed(this, 1000) // Run every 1 second } }
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { startForegroundService() mHandler.post(mRunnable) return START_STICKY }
override fun onBind(intent: Intent?): IBinder? { return null }
private fun checkURL(url: String) { GlobalScope.launch(Dispatchers.IO) { val client = OkHttpClient() val request = Request.Builder() .url(url) .build()
private fun sendNotification(title: String, message: String) { val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val notificationId = 1 val channelId = "background_service_channel" val channelName = "Background Service Channel"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT) channel.lightColor = Color.BLUE channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE notificationManager.createNotificationChannel(channel) }
val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
val notificationBuilder = NotificationCompat.Builder(this, channelId) .setContentTitle(title) .setContentText(message) .setSmallIcon(R.drawable.ic_notification) .setContentIntent(pendingIntent) .setAutoCancel(true)
private fun startForegroundService() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channelId = "background_service_channel" val channelName = "Background Service Channel" val channel = NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT) val notificationManager = getSystemService(NotificationManager::class.java) notificationManager.createNotificationChannel(channel) }
val notification = createNotification() startForeground(NOTIFICATION_ID, notification) }
private fun createNotification(): Notification { val channelId = "background_service_channel" val notificationBuilder = NotificationCompat.Builder(this, channelId) .setContentTitle("Foreground Service") .setContentText("Running...") .setSmallIcon(R.drawable.ic_notification) .setPriority(NotificationCompat.PRIORITY_DEFAULT)
return notificationBuilder.build() }
companion object { private const val NOTIFICATION_ID = 12345678 } } [/code] Мне не удалось ничего найти в сети, поэтому надеюсь, что если я получу ответ, это принесет пользу и другим. Это преследуемая проблема, которая не дает мне спать.😐
Надеюсь, кто -то сможет дать мне несколько предложений по моей проблеме. У меня есть приложение C# фонового обслуживания, где я синхронизирую данные между двумя приложениями. Я создал фоновую службу в C#, которая вызывает задачи синхронизации каждые...
Надеюсь, кто -то сможет дать мне несколько предложений по моей проблеме. У меня есть приложение C# фонового обслуживания, где я синхронизирую данные между двумя приложениями. Я создал фоновую службу в C#, которая вызывает задачи синхронизации каждые...
Надеюсь, кто -то сможет помочь мне с этой проблемой. Я пытаюсь создать фоновую службу, которая синхронизирует данные между двумя приложениями через их API. Эта часть работает. Я хочу, чтобы фоновая служба работала все время, поэтому я создавал...