【问题标题】:Flutter - start foreground service on bootFlutter - 在启动时启动前台服务
【发布时间】:2021-06-01 04:03:34
【问题描述】:

我正在尝试在启动时启动前台服务。 为了实现这一点,我使用flutter_foreground_plugin 我在 android 的应用程序清单中添加了一个 BOOT_COMPLETED 接收器,广播接收器被正确调用,我可以在启动时在其中运行代码。 我的问题很简单——我似乎找不到 changjoopark.com.flutter_foreground_plugin.FlutterForegroundService 插件的正确名称来通过意图启动它。 注意前台插件的包名当然和我的不一样。

以下是 AndroidManifest 的相关摘录:

<receiver android:enabled="true" android:name=".ServiceStartup" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service android:enabled="true" android:name="changjoopark.com.flutter_foreground_plugin.FlutterForegroundService"/>

这是服务启动的代码:

package com.somecompany.myapp;

import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;

public class ServiceStartup extends BroadcastReceiver {

    public void onReceive(final Context context, Intent intent) {
        System.out.println(">>>>>> In onReceive of ServiceStartup <<<<<<< ");
        Handler h = new Handler();
        h.post(new Runnable() {
            @Override
            public void run() {
                Intent intent = new Intent("changjoopark.com.flutter_foreground_plugin.FlutterForegroundService");
                intent.setPackage("changjoopark.com.flutter_foreground_plugin");
                context.startForegroundService(intent);
            }
        });
    }
}

我尝试了所有可能的指定包名称和组件的组合,但似乎都不起作用,因为我在 logcat 中遇到了无法找到组件的错误。 我错过了什么?我应该如何启动服务?

谢谢!

【问题讨论】:

    标签: android flutter package naming foreground-service


    【解决方案1】:

    我知道它已经晚了,但在这里为任何未来的读者回答。

    只有context.startForegroundService(intent); 不会启动服务,因为该包所做的不仅仅是startForegroundService

    检查FlutterForegroundPlugin类中的launchForegroundService方法

    launchForegroundService 执行startForegroundService 然后startServiceLoop

    在 BOOT_COMPLETE 事件中,您需要致电 launchForegroundService。但它是一个私有函数。

    所以在你的广播接收器中执行所有由 launchForegroundService 完成的操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-15
      • 2015-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 1970-01-01
      • 2011-12-03
      相关资源
      最近更新 更多