我有一个简单的 Flutter 应用程序,它使用 MethodChannel
启动 native 后台服务.这个原生后台服务使用 BasicMessageChannel<String>
通知我的 Flutter 应用程序在捕获特定的本地信息时显示文本。当我的应用程序在前台时,所有这些都可以完美运行。当其他应用程序在前台时,我无法看到文本,而无需切换到我的应用程序。
我希望我的原生服务能够显示特定的 Flutter 屏幕,即使其他应用程序正在前台运行。
它可能被认为对用户不友好,但这是一个最重要的信息。
欢迎任何建议或解决方案!
注意: native 服务目前仅适用于 Android 的 Java,我正在为 IOS 端开发 C#。
最佳答案
在 Android 上,您需要显示高优先级通知。这将显示将出现在锁定屏幕或其他应用程序上的向下滑动通知面板。由于您已经在使用 native 代码,您可以在那里创建此通知,或向 Dart 端发送一条消息(正如您所做的那样,使用 MethodChannel
)在那里它可以使用 flutter_local_notifications
插件来显示它。当用户单击通知时,您的 flutter 应用程序将被带到前台。在 Java 中,您可能会使用类似这样的代码:
// Create an intent which triggers the fullscreen notification
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.setAction("SELECT_NOTIFICATION");
Class mainActivityClass = getMainActivityClass(context);
intent.setClass(context, mainActivityClass);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Build the notification as an ongoing high priority item to ensures it will show as
// a heads up notification which slides down over top of the current content.
final Notification.Builder builder = new Notification.Builder(context, CHANNEL_ID);
builder.setOngoing(true);
// Set notification content intent to take user to fullscreen UI if user taps on the
// notification body.
builder.setContentIntent(pendingIntent);
// Set full screen intent to trigger display of the fullscreen UI when the notification
// manager deems it appropriate.
builder.setFullScreenIntent(pendingIntent, true);
// Setup notification content.
int resourceId = context.getResources().getIdentifier("app_icon", "drawable", context.getPackageName());
builder.setSmallIcon(resourceId);
builder.setContentTitle("Your notification title");
builder.setContentText("Your notification content.");
MyPlugin.notificationManager().notify(someId, builder.build());
然后,对于 Android 8.1 或更高版本,将以下内容添加到您的 MainActivity
类中,该类位于 android/app/src/main/java/packageName/文件夹下
GeneratedPluginRegistrant.registerWith(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
setShowWhenLocked(true);
setTurnScreenOn(true);
}
(这会在屏幕锁定时显示 Flutter 应用。)
Flutter 只有一个 Activity ,因此上面的代码会将 Flutter Activity 带到前台(请注意,您并不总是看到通知,但有时您会看到 - 如果您将其设置为 autoCancel 然后触摸它会清除它) .在 Flutter 中构建正确的屏幕取决于您,您可以在发送通知时执行此操作。使用 Navigator.push
或等效的方法来更改 Flutter 正在显示的页面。
关于java - 从 native 后台服务启动屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54054527/