UnhandledException MissingPluginException Flutter, когда метод был реализован - PullRequest
0 голосов
/ 06 мая 2020

Я новичок во Flutter, и я создаю приложение, которое должно иметь возможность устанавливать обои Android из приложения Flutter, если указан URL-адрес изображения. Я написал код, который устанавливает обои на Android по URL-адресу, и он работает. Я перенес код в свой Flutter MainActivity следующим образом:

package com.ngengeapps.wallpapersstock
import android.app.WallpaperManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.AsyncTask
import android.util.Log
import androidx.annotation.NonNull;
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import java.io.IOException
import java.lang.ref.WeakReference
import java.net.HttpURLConnection
import java.net.URL

class MainActivity: FlutterActivity() {
    private val CHANNEL = "com.ngengeapps.wallpapersstock/wallpaper"
    override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
        MethodChannel(flutterEngine.dartExecutor.binaryMessenger,CHANNEL).setMethodCallHandler{
            call,result ->
            if (call.method == "setWallpaper"){
                val urlString = call.argument<String>("url")!!
                val res = setWallpaper(urlString)
                if (res){
                    result.success(res)
                } else{
                    result.error("FAILURE","Failed to set wallpaper","")
                }
            } else {
                result.notImplemented()
            }

        }
        GeneratedPluginRegistrant.registerWith(flutterEngine);
    }


    fun setWallpaper(url: String):Boolean {
        //var result = false
        return try {
            BitMapTask(url, this).execute()
            true
        }
        catch (ex:java.lang.Exception){
            //Toast.makeText(this,)
            false
        }

    }

    companion object {

        class BitMapTask internal constructor(val urlString: String, context: MainActivity) :
                AsyncTask<Unit, Unit, Bitmap?>() {
            private val activityReference: WeakReference<MainActivity> = WeakReference(context)
            override fun doInBackground(vararg params: Unit?): Bitmap? {
                return try {
                    val url = URL(urlString)
                    val conection = url.openConnection() as HttpURLConnection
                    conection.doInput = true
                    val input = conection.inputStream
                    val bitmap = BitmapFactory.decodeStream(input)
                    bitmap
                } catch (ex: IOException) {
                    Log.d("TAG--", "Exception ${ex.localizedMessage}")
                    null
                }
            }

            override fun onPostExecute(result: Bitmap?) {
                super.onPostExecute(result)
                val activity = activityReference.get()
                if (activity != null && !activity.isFinishing) {

                    val wallpaperManager = WallpaperManager.getInstance(activity)
                    try {
                        wallpaperManager.setBitmap(result)
                    } catch (ex: Exception) {
                        Log.d("TAG--", "Error ${ex.localizedMessage}")
                    }
                }
                if (activity == null || activity.isFinishing) return
            }

        }

    }
}

Метод, который мне нужно вызвать во Flutter, - это метод setWallpaper. Вот будущее, о котором я писал, который устанавливает обои при нажатии кнопки с плавающим действием

//At top of file
static const platform =
      const MethodChannel('com.ngengeapps.wallpapersstock/wallpaper');

Future<void> _setWallPaper(String url) async {
    try {
      await platform
          .invokeMethod('setWallpaper', <String, dynamic>{'url': url});
    } on PlatformException catch (e) {
      print("Method call failed ${e.message}");
    }
  }

Кажется, я не вижу, где я ошибся. Пожалуйста, отметьте, если я сделал что-то не так. Вот журнал ошибок

Unhandled Exception: MissingPluginException(No implementation found for method setWallpaper on channel com.ngengeapps.wallpapersstock/wallpaper)
E/flutter (15024): #0      MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7)
E/flutter (15024): <asynchronous suspension>
E/flutter (15024): #1      _FullImageWidgetState._setWallPaper (package:wallpapersstock/FullImage.dart:52:12)
E/flutter (15024): #2      _FullImageWidgetState.build.<anonymous closure> (package:wallpapersstock/FullImage.dart:43:11)
E/flutter (15024): #3      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (15024): #4      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (15024): #5      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (15024): #6      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (15024): #7      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (15024): #8      BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (15024): #9      PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (15024): #10     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (15024): #11     PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (15024): #12     _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (15024): #13     PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (15024): #14     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (15024): #15     GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (15024): #16     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (15024): #17     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (15024): #18     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (15024): #19     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (15024): #20     _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (15024): #21     _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (15024): #22     _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (15024): #23     _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (15024): #24     _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)

1 Ответ

0 голосов
/ 06 мая 2020

Мне пришлось вызвать GeneratedPluginRegistrant.registerWith(flutterEngine) перед вызовом канала метода setMethodCallHandler.

...