Как планировать фоновые задания во Flutter? - программирование
Подтвердить что ты не робот

Как планировать фоновые задания во Flutter?

Я много искал для этого, но не нашел никаких пакетов или способ запланировать фоновые задания в Flutter. Как и в Android, есть WorkManager, AlarmManager.

Я знаю, что могу получить доступ к этим классам с помощью MethodChannel, но мне нужно что-то, что работает для iOS и Android.

(Очень разочаровывает тот факт, что мобильная инфраструктура не имеет возможности планировать фоновые задачи).

4b9b3361

Ответ 1

То, что вы хотите сделать, то есть кросс-платформенное планирование, не является ограничением флаттера. Это ограничение iOS. См. Это сообщение SO, на которое ссылается этот комментарий GitHub.

Ответ 3

Создайте Java файл BroadcastReceiver рядом с MainActivity в каталоге Android.

это содержимое BroadcastReceiver.

package com.example.methodchanel;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.MethodChannel;


public class MyReceiver extends BroadcastReceiver {
    MethodChannel methodChannel;
    MyReceiver(MethodChannel methodChannel){
        this.methodChannel=methodChannel;
    }

    @Override
    public void onReceive(final Context context, Intent intent) {
       methodChannel.invokeMethod("I say hello every minute!!","");
    }
}

Добавьте эти коды перед тегом в AndroidManifest.xml.

<receiver
            android:name=".MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter >
                <action android:name="android.intent.action.TIME_TICK"/>
            </intent-filter>
        </receiver>

Отредактируйте MainActivity.java следующим образом

package com.example.methodchanel;

import android.content.IntentFilter;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import android.content.Intent;

public class MainActivity extends FlutterActivity {

  private static final String CHANNEL = "com.example";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    MethodChannel methodChannel = new MethodChannel(getFlutterView(), CHANNEL);
    MyReceiver receiver = new MyReceiver(methodChannel);
    IntentFilter mTime = new IntentFilter(Intent.ACTION_TIME_TICK);
    registerReceiver(receiver, mTime);
  }
}

в флаттер main.dart добавьте эти коды после

класс _MyHomePageState расширяет состояние {

static const methodChannel = const MethodChannel('com.example');
  _MyHomePageState() {
    methodChannel.setMethodCallHandler((call) {
      print(call.method);
    });
  }

Хорошо!! , это почти сделано!

Android посылает сигнал каждую минуту, чтобы трепетать. другими словами, ваш код флаттера выполняется каждую 1 минуту. Даже вы сверните свое приложение Flutter или переключиться на другие приложения на вашем телефоне!

В этом суть.