Wes*_*y92 13 android android-widget dart flutter flutter-plugin
我在Flutter应用程序中添加了原生Android主屏幕小部件.
在我的AppWidgetProvider实现中,我想onUpdate()使用平台通道在我的方法中调用dart代码.
这可能吗?如果是这样,怎么能实现呢?
我目前的Android(Java)代码:
package com.westy92.checkiday;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.util.Log;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.view.FlutterNativeView;
public class HomeScreenWidget extends AppWidgetProvider {
private static final String TAG = "HomeScreenWidget";
private static final String CHANNEL = "com.westy92.checkiday/widget";
private static FlutterNativeView backgroundFlutterView = null;
private static MethodChannel channel = null;
@Override
public void onEnabled(Context context) {
Log.i(TAG, "onEnabled!");
backgroundFlutterView = new FlutterNativeView(context, true);
channel = new MethodChannel(backgroundFlutterView, CHANNEL);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
Log.i(TAG, "onUpdate!");
if (channel != null) {
Log.i(TAG, "channel not null, invoking dart method!");
channel.invokeMethod("foo", "extraJunk");
Log.i(TAG, "after invoke dart method!");
}
}
}
Run Code Online (Sandbox Code Playgroud)
飞镖码:
void main() {
runApp(Checkiday());
}
class Checkiday extends StatefulWidget {
@override
_CheckidayState createState() => _CheckidayState();
}
class _CheckidayState extends State<Checkiday> {
static const MethodChannel platform = MethodChannel('com.westy92.checkiday/widget');
@override
void initState() {
super.initState();
platform.setMethodCallHandler(nativeMethodCallHandler);
}
Future<dynamic> nativeMethodCallHandler(MethodCall methodCall) async {
print('Native call!');
switch (methodCall.method) {
case 'foo':
return 'some string';
default:
// todo - throw not implemented
}
}
@override
Widget build(BuildContext context) {
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
当我将小部件添加到我的主屏幕时,我看到:
I/HomeScreenWidget(10999): onEnabled!
I/HomeScreenWidget(10999): onUpdate!
I/HomeScreenWidget(10999): channel not null, invoking dart method!
I/HomeScreenWidget(10999): after invoke dart method!
Run Code Online (Sandbox Code Playgroud)
但是,我的dart代码似乎没有接收到调用.
我还需要一些本机 Android 小部件来与我的 dart 代码进行通信,经过一番修改后我设法做到了这一点。在我看来,关于如何做到这一点的文档有点稀疏,但凭借一点创造力,我设法让它发挥作用。我还没有做足够的测试来称其为 100% 生产就绪,但它似乎正在工作......
飞镖设置
转到main.dart并添加以下顶级函数:
void initializeAndroidWidgets() {
if (Platform.isAndroid) {
// Intialize flutter
WidgetsFlutterBinding.ensureInitialized();
const MethodChannel channel = MethodChannel('com.example.app/widget');
final CallbackHandle callback = PluginUtilities.getCallbackHandle(onWidgetUpdate);
final handle = callback.toRawHandle();
channel.invokeMethod('initialize', handle);
}
}
Run Code Online (Sandbox Code Playgroud)
然后在运行您的应用程序之前调用此函数
void main() {
initializeAndroidWidgets();
runApp(MyApp());
}
Run Code Online (Sandbox Code Playgroud)
这将确保我们可以在本机端获取入口点的回调句柄。
现在添加一个入口点,如下所示:
void onWidgetUpdate() {
// Intialize flutter
WidgetsFlutterBinding.ensureInitialized();
const MethodChannel channel = MethodChannel('com.example.app/widget');
// If you use dependency injection you will need to inject
// your objects before using them.
channel.setMethodCallHandler(
(call) async {
final id = call.arguments;
print('on Dart ${call.method}!');
// Do your stuff here...
final result = Random().nextDouble();
return {
// Pass back the id of the widget so we can
// update it later
'id': id,
// Some data
'value': result,
};
},
);
}
Run Code Online (Sandbox Code Playgroud)
该函数将成为我们的小部件的入口点,并在onUpdate调用我们的小部件方法时被调用。然后我们可以传回一些数据(例如在调用 api 之后)。
安卓设置
这里的示例是用 Kotlin 编写的,但经过一些细微的调整也应该可以在 Java 中使用。
创建一个WidgetHelper类来帮助我们存储和获取入口点的句柄:
class WidgetHelper {
companion object {
private const val WIDGET_PREFERENCES_KEY = "widget_preferences"
private const val WIDGET_HANDLE_KEY = "handle"
const val CHANNEL = "com.example.app/widget"
const val NO_HANDLE = -1L
fun setHandle(context: Context, handle: Long) {
context.getSharedPreferences(
WIDGET_PREFERENCES_KEY,
Context.MODE_PRIVATE
).edit().apply {
putLong(WIDGET_HANDLE_KEY, handle)
apply()
}
}
fun getRawHandle(context: Context): Long {
return context.getSharedPreferences(
WIDGET_PREFERENCES_KEY,
Context.MODE_PRIVATE
).getLong(WIDGET_HANDLE_KEY, NO_HANDLE)
}
}
}
Run Code Online (Sandbox Code Playgroud)
将您的替换MainActivity为:
class MainActivity : FlutterActivity(), MethodChannel.MethodCallHandler {
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
GeneratedPluginRegistrant.registerWith(flutterEngine)
val channel = MethodChannel(flutterEngine.dartExecutor.binaryMessenger, WidgetHelper.CHANNEL)
channel.setMethodCallHandler(this)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"initialize" -> {
if (call.arguments == null) return
WidgetHelper.setHandle(this, call.arguments as Long)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这将简单地确保我们存储句柄(入口点的哈希值)以便SharedPreferences稍后能够在小部件中检索它。
现在修改你的AppWidgetProvider看起来类似于这样:
class Foo : AppWidgetProvider(), MethodChannel.Result {
private val TAG = this::class.java.simpleName
companion object {
private var channel: MethodChannel? = null;
}
private lateinit var context: Context
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) {
this.context = context
initializeFlutter()
for (appWidgetId in appWidgetIds) {
updateWidget("onUpdate ${Math.random()}", appWidgetId, context)
// Pass over the id so we can update it later...
channel?.invokeMethod("update", appWidgetId, this)
}
}
private fun initializeFlutter() {
if (channel == null) {
FlutterMain.startInitialization(context)
FlutterMain.ensureInitializationComplete(context, arrayOf())
val handle = WidgetHelper.getRawHandle(context)
if (handle == WidgetHelper.NO_HANDLE) {
Log.w(TAG, "Couldn't update widget because there is no handle stored!")
return
}
val callbackInfo = FlutterCallbackInformation.lookupCallbackInformation(handle)
// You could also use a hard coded value to save you from all
// the hassle with SharedPreferences, but alas when running your
// app in release mode this would fail.
val entryPointFunctionName = callbackInfo.callbackName
// Instantiate a FlutterEngine.
val engine = FlutterEngine(context.applicationContext)
val entryPoint = DartEntrypoint(FlutterMain.findAppBundlePath(), entryPointFunctionName)
engine.dartExecutor.executeDartEntrypoint(entryPoint)
// Register Plugins when in background. When there
// is already an engine running, this will be ignored (although there will be some
// warnings in the log).
GeneratedPluginRegistrant.registerWith(engine)
channel = MethodChannel(engine.dartExecutor.binaryMessenger, WidgetHelper.CHANNEL)
}
}
override fun success(result: Any?) {
Log.d(TAG, "success $result")
val args = result as HashMap<*, *>
val id = args["id"] as Int
val value = args["value"] as Int
updateWidget("onDart $value", id, context)
}
override fun notImplemented() {
Log.d(TAG, "notImplemented")
}
override fun error(errorCode: String?, errorMessage: String?, errorDetails: Any?) {
Log.d(TAG, "onError $errorCode")
}
override fun onDisabled(context: Context?) {
super.onDisabled(context)
channel = null
}
}
internal fun updateWidget(text: String, id: Int, context: Context) {
val views = RemoteViews(context.packageName, R.layout.small_widget).apply {
setTextViewText(R.id.appwidget_text, text)
}
val manager = AppWidgetManager.getInstance(context)
manager.updateAppWidget(id, views)
}
Run Code Online (Sandbox Code Playgroud)
这里重要的是initializeFlutter确保我们能够获得入口点的句柄。然后onUpdate,我们调用这将触发前面定义的 dart 端的channel?.invokeMethod("update", appWidgetId, this)回调。MethodChannel然后我们稍后处理结果success(至少在调用成功时)。
希望这能让您大致了解如何实现这一目标......
首先,请确保您在尝试执行任何 Dart 代码之前调用FlutterMain.startInitialization()then 。FlutterMain.ensureInitializationComplete()这些调用是引导 Flutter 所必需的。
其次,您可以使用新的实验性 Android 嵌入来尝试同样的目标吗?
以下是使用新嵌入执行 Dart 代码的指南: https://github.com/flutter/flutter/wiki/Experimental :-Reuse-FlutterEngine-across-screens
如果您的代码在新的 Android 嵌入中仍然无法按预期工作,那么应该更容易调试问题所在。请发回成功信息,或者任何新的错误信息。
| 归档时间: |
|
| 查看次数: |
1264 次 |
| 最近记录: |