Пользовательский фоновый сервис FlutterAndroid

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Anonymous
 Пользовательский фоновый сервис Flutter

Сообщение Anonymous »

Я хочу создать фоновую службу для проверки URL-адреса и отправки уведомления пользователю, если код состояния равен 200.
У меня есть две проблемы:
  • Раздражающее уведомление для службы переднего плана (если я его не отправлю, моя служба не будет работать, когда пользователь закроет приложение)
  • Я хочу иметь возможность передавать URL-адрес из файла dart в мой файл kt.
Вот код:
Main.dart

Код: Выделить всё

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');

Future  startService() async {
try {
await platform.invokeMethod('startService');
} on PlatformException catch (e) {
print("Failed to start service: '${e.message}'.");
}
}

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Background Service Demo'),
),
body: Center(
child: ElevatedButton(
onPressed: () {
startService();
},
child: Text('Start Service'),
),
),
),
);
}
}
MainActivity.kt

Код: Выделить всё

package com.example.flutter_application_1

import android.content.Intent // Import Intent
import android.os.Bundle
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel

class MainActivity : FlutterActivity() {
private val CHANNEL = "com.example.background_service"

override fun configureFlutterEngine(flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "startService") {
startService(Intent(this, BackgroundService::class.java))
result.success(null)
} else {
result.notImplemented()
}
}
}
}
и код фоновой службы
BackgroundService.kt

Код: Выделить всё

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
}
}
Мне не удалось ничего найти в сети, поэтому надеюсь, что если я получу ответ, это принесет пользу и другим.
Это преследуемая проблема, которая не дает мне спать.😐

Подробнее здесь: https://stackoverflow.com/questions/782 ... nd-service
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Как начать свой фоновый сервис C# в Azure?
    Anonymous » » в форуме C#
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous
  • Как начать свой фоновый сервис C# в Azure?
    Anonymous » » в форуме C#
    0 Ответы
    4 Просмотры
    Последнее сообщение Anonymous
  • Как начать свой фоновый сервис C# в Azure? [закрыто]
    Anonymous » » в форуме C#
    0 Ответы
    5 Просмотры
    Последнее сообщение Anonymous
  • Почему кажется невозможным разработать стабильный фоновый сервис на Android?
    Anonymous » » в форуме Android
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Сервис с таймером вызывает другой сервис
    Anonymous » » в форуме JAVA
    0 Ответы
    16 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Android»