Необработанное исключение Flutter MethodChannel: MissingPluginException(не найдено реализации для метода startService на канале com.mypackage.messages)
Итак, здесь я пытаюсь реализовать свой MethodChannel на Flutter.
Вот некоторые из моих фрагментов кода.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.mypackage">
<!-- rest of the code -->
<application
android:requestLegacyExternalStorage="true"
android:allowBackup="false"
android:name=".Application"
android:label="My App Name"
android:usesCleartextTraffic="true"
tools:replace="android:label"
android:icon="@mipmap/ic_launcher">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="@drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
<!-- rest of the code -->
</application>
А так выглядит моя MainActivity
public class MainActivity extends FlutterActivity {
private Intent forService;
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine);
forService = new Intent(this, MyService.class);
new MethodChannel(flutterEngine.getDartExecutor().getBinaryMessenger(), "com.mypackage.messages")
.setMethodCallHandler(
(methodCall, result) -> {
Log.d("method", "method " + methodCall.method);
if (methodCall.method.equals("startService")) {
startService();
result.success("Service Started");
}
if (methodCall.method.equals("stopService")) {
stopService();
result.success("Service Stoped");
}
}
);
}
private void startService() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(forService);
} else {
startService(forService);
}
}
private void stopService() {
stopService(forService);
}
}
И вот как я вызываю свой собственный MethodChannel со стороны Dart.
if (Platform.isAndroid) {
var methodChannel = MethodChannel("com.mypackage.messages");
String data = await methodChannel.invokeMethod("startService");
debugPrint(data);
}
Я поместил приведенный выше код в main.dart. На самом деле я использую AlarmManager, обратный вызов которого будет вызываться в определенное время. И этот обратный вызов должен вызывать метод startService, который я уже определил в моем MethodChannel.
Но когда приходит время, и он вызывает метод, он говорит
Unhandled Exception: MissingPluginException(No implementation found for method startService on channel com.mypackage.messages)
Я нашел много ответов в SO и Github, в которых обсуждалась подобная ошибка, за исключением того, что все упомянутые там случаи произошли, когда кто-то внедрял другие плагины. В этом случае я делаю свой собственный MethodChannel.
Так что мне просто было интересно, какая часть конфигурации MethodChannel мне может здесь не хватать, или что-то я делаю не так. Любая помощь будет очень признательна.