Buscar pacotes, repositórios e categorias de apps

Detalhes do pacotev0.4.0

background_task

Pode ser processado usando atualizações de localização após o aplicativo passar para o fundo.

AndroidiOS
Downloads em 30 dias
97
Curtidas
40
Pontos Pub
160

Instalar pacote

flutter pub add background_task

Visão geral do pacote

Orientação gerada a partir de informações públicas. Apenas para referência.

O pacote background_task permite que aplicativos Flutter realizem operações, especialmente atualizações de localização, mesmo quando o app está em segundo plano. Foi projetado para Android e iOS, permitindo que desenvolvedores mantenham funcionalidades contínuas, como rastrear o movimento do usuário sem interrupções. O pacote integra-se aos recursos nativos da plataforma para garantir execução confiável durante os estados em segundo plano. É especialmente útil para aplicativos que exigem monitoramento de localização em tempo real ou coleta periódica de dados. A solução é construída com sobreposição mínima e oferece suporte a ambas as plataformas por meio de implementações nativas dedicadas.

Casos de uso

  • Rastreamento de localização em tempo real
  • Sincronização periódica de dados
  • Geofencing em segundo plano
  • execução de tarefa de longa duração
  • Processamento em segundo plano eficiente em bateria

Principais recursos

  • Suporta Android e iOS
  • Gerencia atualizações de localização em segundo plano
  • Impacto mínimo na bateria
  • Integração com plataforma nativa
  • API simples para agendamento de tarefas

Indicado para

  • Aplicativos de fitness e navegação
  • Logística e rastreamento de entrega
  • Gestão de Serviços em Campo
  • Aplicativos que exigem atividade contínua em segundo plano
  • Serviços baseados em localização

Considerações

  • Requer permissões adequadas em ambas as plataformas
  • Pode ser restrito por modos de economia de energia do sistema operacional
  • Necessita de testes em dispositivos reais
  • Os limites de execução em segundo plano variam conforme a versão do sistema operacional
  • O usuário deve conceder acesso à localização

README original

Snapshot do README original do repositório-fonte vinculado. Consulte o repositório para o conteúdo mais recente.

background_task

never-light-log

Developed with 💙 by Never inc.


Motivation

Enable developers to continue processing even when the application transitions to the background, we have created a package that allows processing to continue using location updates.This package was created with reference to background_location.

Can be used when you want to run the program periodically in the background.

  • Monitor and notify the distance walked and steps.
  • Notification of destination arrival.
  • Tracking location information (sending it to a server).

Usage

// Monitor notifications of background processes.
// However, Cannot be used while the app is in task kill.
BackgroundTask.instance.stream.listen((event) {
  // Implement the process you want to run in the background.
  // ex) Check health data.
});

// Start background processing with location updates.
await BackgroundTask.instance.start();

// Stop background processing and location updates.
await BackgroundTask.instance.stop();

This is an implementation for receiving updates even when the task is task-killed. In this package, iOS uses startMonitoringSignificantLocationChanges and Android uses ForegroundService.

// Define callback handler at the top level.
@pragma('vm:entry-point')
void backgroundHandler(Location data) {
  // Implement the process you want to run in the background.
  // ex) Check health data.
}

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  BackgroundTask.instance.setBackgroundHandler(backgroundHandler); // 👈 Set callback handler.
  runApp(const MyApp());
}

To get the latest location information in a task-killed status, set the app to Always.

ios android

This is an implementation for when you want to stop using the application when it is killed.

await BackgroundTask.instance.start(
  isEnabledEvenIfKilled: false,
);

Recommended to use with permission_handler.

final status = await Permission.location.request();
final statusAlways = await Permission.locationAlways.request();

if (status.isGranted && statusAlways.isGranted) {
  await BackgroundTask.instance.start();
}
Setup

pubspec.yaml

dependencies:
  background_task:

iOS: Info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Used to monitor location in the background and notify to app.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Used to monitor location in the background and notify to app.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Used to monitor location in the background and notify to app.</string>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>location</string>
</array>

To use an external package (shared_preference etc..) in callback handler, register DispatchEngine in AppDelegate.

iOS: AppDelegate.swift

import UIKit
import Flutter
import background_task // 👈 Add

@main
@objc class AppDelegate: FlutterAppDelegate, FlutterImplicitEngineDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      GeneratedPluginRegistrant.register(with: self)
      // 👇 Add
      BackgroundTaskPlugin.onRegisterDispatchEngine = {
          GeneratedPluginRegistrant.register(with: BackgroundTaskPlugin.dispatchEngine)
      }
      return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

  func didInitializeImplicitFlutterEngine(_ engineBridge: FlutterImplicitEngineBridge) {
    GeneratedPluginRegistrant.register(with: engineBridge.pluginRegistry)
  }
}

Android: AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

References

Categorias

Repositório-fonte

Projetos que usam este pacote

Ainda não há dados.