如何在Flutter插件中获取活动和上下文 [英] How to get Activity and Context in Flutter plugin

查看:1595
本文介绍了如何在Flutter插件中获取活动和上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个包裹需要访问 Context ,而我是从 onAttachedToEngine -> flutterPluginBinding.getApplicationContext()到变量,但这会导致 NullPointerException 使应用程序崩溃。原因是我认为我正在尝试将 Context 分配给变量。

One of my package need to access Context and I got it from onAttachedToEngine -> flutterPluginBinding.getApplicationContext() to a variable but this crash the app with NullPointerException. The reason is I think I am trying to use the Context before it is assigning to the variable.

什么是正确的方式访问 Context

What is the correct way to access the Context?

如何获得 Activity 如果我也想要?

And how can I get the Activity if I wanted too?

推荐答案

取决于 Create-Flutter-Plugin ,请按照以下步骤操作:

Depends on flutter document in Create-Flutter-Plugin, Follow these steps:

1-导入ActivityAware:

1- Import ActivityAware:

import io.flutter.embedding.engine.plugins.activity.ActivityAware

2-在您的班级实施ActivityAware:

2- implement ActivityAware in your class:

public class ClassName: FlutterPlugin, MethodCallHandler, ActivityAware { 

3-定义要使用它的 lateinit 变量类:

3- Define lateinit variables to use it class:

private lateinit var context: Context
private lateinit var activity: Activity

4-添加以下功能:

override fun onDetachedFromActivity() {
    TODO("Not yet implemented")
}

override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    TODO("Not yet implemented")
}

override fun onAttachedToActivity(binding: ActivityPluginBinding) {
    activity = binding.activity;
}

override fun onDetachedFromActivityForConfigChanges() {
    TODO("Not yet implemented")
}

5-在onAttachedToEngine函数中添加以下行:

5- Add this line in onAttachedToEngine function:

context = flutterPluginBinding.applicationContext

您可以看到以下完整代码以了解更多信息:

You can see this full code for more understanding:

package com.example.flutter_plugin_name

import android.app.Activity
import android.content.Context
import androidx.annotation.NonNull;
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar


public class FlutterPluginName: FlutterPlugin, MethodCallHandler, ActivityAware {
  /// The MethodChannel that will the communication between Flutter and native Android
  ///
  /// This local reference serves to register the plugin with the Flutter Engine and unregister it
  /// when the Flutter Engine is detached from the Activity
  private lateinit var channel : MethodChannel

    private lateinit var context: Context
    private lateinit var activity: Activity

  override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
    channel = MethodChannel(flutterPluginBinding.getFlutterEngine().getDartExecutor(), "flutter_plugin_name")
    channel.setMethodCallHandler(this);
    context = flutterPluginBinding.applicationContext
  }



  // This static function is optional and equivalent to onAttachedToEngine. It supports the old
  // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
  // plugin registration via this function while apps migrate to use the new Android APIs
  // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
  //
  // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
  // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
  // depending on the user's project. onAttachedToEngine or registerWith must both be defined
  // in the same class.
  companion object {
    @JvmStatic
    fun registerWith(registrar: Registrar) {
      val channel = MethodChannel(registrar.messenger(), "flutter_plugin_name")
      channel.setMethodCallHandler(FlutterMapboxTurnByTurnPlugin())
    }
  }

  override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
    if (call.method == "getPlatformVersion") {
      result.success("Android ${android.os.Build.VERSION.RELEASE}")
    }

    else {
      result.notImplemented()
    }
  }

  override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
    channel.setMethodCallHandler(null)
  }

    override fun onDetachedFromActivity() {
        TODO("Not yet implemented")
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
        TODO("Not yet implemented")
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity;
    }

    override fun onDetachedFromActivityForConfigChanges() {
        TODO("Not yet implemented")
    }
}

这篇关于如何在Flutter插件中获取活动和上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆