我想在 Flutter 中处理 FCM 的后台消息,但是当 fcm 在后台模式下向应用程序发送消息并在日志中出错时出现错误
pubspec.yaml:
firebase_core: ^0.7.0
firebase_messaging: ^8.0.0-dev.14
Run Code Online (Sandbox Code Playgroud)
主活动.kt :
package com.mydomain.myproject
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
Run Code Online (Sandbox Code Playgroud)
应用程序.kt :
package com.mydomain.myproject
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundExecutor
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin
import io.flutter.plugins.pathprovider.PathProviderPlugin
class MyApplication : FlutterApplication(), PluginRegistrantCallback {
override
fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingBackgroundService.setPluginRegistrant(this)
FlutterFirebaseMessagingBackgroundExecutor.setPluginRegistrant(this)
}
override
fun registerWith(registry: PluginRegistry) {
PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin"))
FlutterLocalNotificationsPlugin.registerWith(registry.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"))
FlutterFirebaseMessagingPlugin.registerWith(registry.registrarFor("plugins.flutter.io/firebase_messaging"))
}
}
Run Code Online (Sandbox Code Playgroud)
使用fcm的代码: 我只是在主应用程序类的initState()中调用了_initFcm()。我的目标是当应用程序在后台时,后台 fcm 方法必须触发,我必须在首选项中保存消息数据,以便在应用程序打开时做一些事情
void _initFcm() {
Firebase.initializeApp();
FirebaseMessaging.onMessageOpenedApp.listen((message) {
Logger.log("_messaging onMessageOpenedApp: ${message}"); …Run Code Online (Sandbox Code Playgroud) firebase flutter firebase-cloud-messaging flutter-method-channel
我正在使用 Java 为 Android 开发 Flutter 插件。当我调用MethodChannel时,我需要调用另一个Android Intent。如果我使用本机活动,那就很简单,因为我可以在同一个类上调用startActivityForResult和实现该方法。onActivityResult
但是,当我开发 Flutter 插件时,我可以实现FlutterPlugin、MethodCallHandler和ActivityAware接口,但如何启动一个新活动并监听异步结果?
Java代码:
public class GetnetPlugin implements FlutterPlugin, MethodCallHandler, ActivityAware {
private MethodChannel channel;
private Context context;
private Activity activity;
@Override
public void onAttachedToEngine(@NonNull FlutterPluginBinding flutterPluginBinding) {
context = flutterPluginBinding.getApplicationContext();
channel = new MethodChannel(flutterPluginBinding.getBinaryMessenger(), "com.example/method");
channel.setMethodCallHandler(this);
}
@Override
public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) {
channel.setMethodCallHandler(null);
}
@Override
public void onMethodCall(@NonNull MethodCall call, @NonNull Result result) {
switch (call.method){
case "makePayment":
makePayment();
result.success(true); …Run Code Online (Sandbox Code Playgroud) android-intent flutter startactivityforresult flutter-method-channel
TL;DR 如何让 Android 传感器永久运行/活动/注册我的应用程序,即使我关闭它?
目标:
我正在制作一个 Flutter 应用程序,它使用计步器包来计算您的步数,
该包
使用Android 的内置传感器,TYPE_STEP_COUNTER返回自上次启动(iOS)以来所采取的步数。在 Android 上,安装应用程序之前执行的任何步骤均不计算在内。
我是如何实现的:
myStepCount加 1。TYPE_STEP_COUNTER传感器应该仍然在后台运行stepCount,一旦我再次打开我的应用程序,新的和上次保存的stepCount(保存的)之间的差异使用shared_prefs)将被计算并添加到myStepCount.重要提示:即使在我锁定手机、转到主屏幕或关闭应用程序之后,
传感器TYPE_STEP_COUNTER也必须在后台永久运行/保持注册状态...
观察结果:
TYPE_STEP_COUNTER已永久注册)。myStepCount当应用程序在前台运行时采取步骤时,该值会增加。但是,一旦我再次打开应用程序,就不会添加关闭myStepCount应用程序时采取的步骤。结论:
我需要找到一种方法从我的 Flutter 应用程序注册TYPE_STEP_COUNTER传感器,并在关闭应用程序后保持其注册状态。
2 尝试过(但不成功)的解决方案:
第一次尝试: …
android-sensors sensormanager flutter pedometer flutter-method-channel
我目前正在尝试在我的 Flutter 应用程序中实现 FCM 和本地通知。我已经成功配置了 FCM 和普通通知的本地通知,但我还有一种不同类型的通知,我想用图像显示,当我的应用程序在前台时,通知显示没有错误,但是当我终止时应用程序/将其移动到后台我在尝试使用路径提供程序保存图像时出现异常。
例外:
MissingPluginException(No implementation found for method getApplicationDocumentsDirectory on channel plugins.flutter.io/path_provider)
Run Code Online (Sandbox Code Playgroud)
我假设发生此错误是因为当应用程序不在前台时路径提供程序方法通道已关闭,我可以做些什么来解决这个问题?或者,如果flutter_local_notifications插件不需要位图的文件路径,我是否可以实现保存图像并以不同的方式获取路径以在后台工作(没有路径提供程序)?(我实际上想要显示的是来自这样一个链接的图像:https : //is1-ssl.mzstatic.com/image/thumb/WNUBiv2P6YSklHn9eA5nlg/1000x1000bb.jpeg)
保存图像:
static Future<String> saveImage(Image image) {
final completer = Completer<String>();
image.image.resolve(ImageConfiguration()).addListener(ImageStreamListener((imageInfo,_) async {
final byteData = await imageInfo.image.toByteData(format: ImageByteFormat.png);
final pngBytes = byteData.buffer.asUint8List();
final fileName = pngBytes.hashCode;
final directory = await getApplicationDocumentsDirectory();
final filePath = '${directory.path}/$fileName';
final file = File(filePath);
await file.writeAsBytes(pngBytes);
completer.complete(filePath);
}));
return completer.future;
}
Run Code Online (Sandbox Code Playgroud) notifications image flutter firebase-cloud-messaging flutter-method-channel
我正在 Flutter 应用程序中开发本机 Android 小部件。其中有刷新按钮,点击后我必须在 Flutter 代码中调用一个方法。我正在使用 Flutter Method Channel 进行通信,并且当应用程序处于前台时它工作正常。但是当应用程序最小化或关闭时它不起作用。我收到错误PlatformException(NO_ACTIVITY, null, null)。下面是我的代码。
安卓(AppWidgetProvider)
if (methodChannel == null && context != null) {
FlutterMain.startInitialization(context)
FlutterMain.ensureInitializationComplete(context, arrayOf())
// Instantiate a FlutterEngine.
val engine = FlutterEngine(context.applicationContext)
// Define a DartEntrypoint
val entrypoint: DartEntrypoint = DartEntrypoint.createDefault()
// Execute the DartEntrypoint within the FlutterEngine.
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 …Run Code Online (Sandbox Code Playgroud) 我正在尝试从本机 Android 打开颤动屏幕
所以我尝试使用 MethodChannel 将数据返回到 dart,然后调用将我导航到当前屏幕的方法
但我的代码不起作用
这是我的代码
@Override
public void configureFlutterEngine(@NonNull FlutterEngine flutterEngine) {
super.configureFlutterEngine(flutterEngine);
String channelName = "app_channel";
MethodChannel methodChannel = new MethodChannel(flutterEngine.getDartExecutor(), channelName);
methodChannel.invokeMethod("openCaller", false, new MethodChannel.Result() {
@Override
public void success(@Nullable Object result) {
Log.i("fromInvoke","success" + result.toString());
}
@Override
public void error(String errorCode, @Nullable String errorMessage, @Nullable Object errorDetails) {
Log.i("fromInvoke","failed" + errorMessage);
}
@Override
public void notImplemented() {
Log.i("fromInvoke","not implemented");
}
});
}
Run Code Online (Sandbox Code Playgroud)
}
static const platform =
const MethodChannel('app_channel');
@override
void initState() { …Run Code Online (Sandbox Code Playgroud) 刚刚创建了一个新的 Flutter 应用程序
当我收到通知时(想想电话),最终尝试打开我的应用程序或显示全屏活动
目前只是尝试控制台登录通过后台消息处理程序调用的本机类
当我发送通知时收到此错误,您看到我做错了什么吗?我应该有不同的方法来处理这个问题吗?
D/FLTFireMsgReceiver(17161): broadcast received for message
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(I)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->add(ILjava/lang/String;)Z (greylist,test-api, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->get(I)I (greylist, reflection, allowed)
W/com.myapp(17161): Accessing hidden method Landroid/os/WorkSource;->getName(I)Ljava/lang/String; (greylist, reflection, allowed)
I/flutter (17161): FlutterFire Messaging: An error occurred in your background messaging handler:
I/flutter (17161): MissingPluginException(No implementation found for method getBatteryLevel on channel samples.flutter.dev/battery)
Run Code Online (Sandbox Code Playgroud)
主程序.dart
...
Future<void> backgroundHandler(RemoteMessage message) async {
const platform = const MethodChannel('samples.flutter.dev/battery'); …Run Code Online (Sandbox Code Playgroud) android kotlin flutter firebase-cloud-messaging flutter-method-channel
我在 Android 构建的 MainActivity 类中注册了一个方法通道,当从前台应用程序调用时该方法可以正常工作。
我想从 Workmanager 在后台运行的任务中调用此方法通道,但每次都会收到 MissingPluginException。
我猜这不起作用,因为后台任务不会初始化 MainActivity,但我似乎找不到有关如何在工作管理器可以调用它们的地方注册通道的任何信息。
我的(简化的)设置如下:lib/main.dart:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
Workmanager().initialize(callbackDispatcher, isInDebugMode: true);
Workmanager().registerPeriodicTask('uniquename', 'taskName',
frequency: const Duration(minutes: 15),
constraints: Constraints(networkType: NetworkType.connected));
runApp(const MyApp());
}
void callbackDispatcher() {
Workmanager().executeTask((taskName, inputData) async {
bool result = await DeviceInfoModel().getDeviceInfo();
return Future.value(result);
});
}
Run Code Online (Sandbox Code Playgroud)
lib/device_info.dart:
class DeviceInfoModel extends ChangeNotifier {
static const platform = MethodChannel('deviceInfo');
Future<void> getDeviceInfo() async {
final int result = await platform.invokeMethod('getBatteryLevel');
// And other similar calls to other methods
}
}
Run Code Online (Sandbox Code Playgroud)
android/app/src/main/kotlin/nl/myapp/MainActivity.kt: …
在开始我的问题之前,我想指出它与这个问题不相似。 编写平台特定代码与 dart:ffi 代码之间的区别。在这里,提问者询问实际的差异,而我试图了解使用两种方法可以实现的相同任务的差异。
在平台上运行原生 c/c++ 代码,在平台端获取结果(例如 Kotlin)并通过方法通道将其发送到 dart 与编写接口dart:ffi并直接调用原生 c++ 代码有什么区别。它们基本上将提供相同的代码执行。我看到的唯一区别是 MethodChannel 调用将是异步任务与dart:ffi同步任务。除了异步行为之外,从任一技术获取响应是否会有任何差异(主要是性能)。
我是 flutter 的新手,我想更改设备的壁纸,但这需要来自平台通道 https://developer.android.com/reference/android/Manifest.permission?hl=en#SET_WALLPAPER 和 本机 android wallpaperManager 的方法调用
在 android 文件夹 /MainActivity.kt Kotlin 文件下抛出错误。
我尝试了以下这些:
我从这里阅读了有关其他类型不匹配错误问题的信息,但不幸的是没有找到任何内容。
任何帮助都适用。我的代码如下。
MainActivity.kt
package com.combasis.wallpaper_son_app
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugins.GeneratedPluginRegistrant
import java.io.IOException
import android.app.WallpaperManager
import android.graphics.BitmapFactory
import java.io.File
import android.os.Build
import android.annotation.TargetApi
import android.content.Context
import io.flutter.Log
private const val CHANNEL = "com.combasis.wallpaper_son_app"
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "setWallpaper") {
val …Run Code Online (Sandbox Code Playgroud) 目标:我使用 flutter 创建了一个音乐播放器。我想播放另一个应用程序中的音频文件。为此,我使用了方法通道在 flutter 和 Android 之间进行通信。并且我从 Intent 获取了以下 URI。
Received URI:content://com.mi.android.globalFileexplorer.myprovider/external_files/song.mp3
Received PATH:/external_files/song.mp3
Run Code Online (Sandbox Code Playgroud)
我的代码
private MediaMetadataRetriever song details;
private MetadataDetails[] songDetails;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
songDetails = new MediaMetadataRetriever();
Intent intent = getIntent();
new MethodChannel(AudioServicePlugin.getFlutterEngine(this).getDartExecutor().getBinaryMessenger(), CHANNEL).setMethodCallHandler(
(call, result) -> {
if (call.method.equals("song")) {
if(intent != null && intent.getData() !=null) {
songDetails.setDataSource(intent.getData().getPath());
result.success(songDetails);
}
else {
result.success(null);
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
当我获取歌曲详细信息时,出现以下错误。
ERROR:setDataSource failed: status = 0xFFFFFFEA
Run Code Online (Sandbox Code Playgroud)
我已经尝试过下面的代码。
FileInputStream file = new FileInputStream(intent.getData().getPath());
songDetails.setDataSource(file.getFD());
Run Code Online (Sandbox Code Playgroud)
但这对我不起作用。
谁能指导我如何去做?