以下是Flutter调用Kotlin编写的生成App桌面快捷方式和检查是否生成App桌面快捷方式的完整代码:

  1. 生成App桌面快捷方式

Kotlin代码:

fun createShortcut(context: Context, appName: String, iconResId: Int, intent: Intent) {
    if (ShortcutManagerCompat.isRequestPinShortcutSupported(context)) {
        val shortcutManager = context.getSystemService(ShortcutManager::class.java)
        val shortcut = ShortcutInfoCompat.Builder(context, appName)
            .setIcon(IconCompat.createWithResource(context, iconResId))
            .setIntent(intent)
            .setShortLabel(appName)
            .build()
        val pinnedShortcutCallbackIntent =
            shortcutManager!!.createShortcutResultIntent(shortcut)
        val successCallback =
            PendingIntent.getBroadcast(context, 0, pinnedShortcutCallbackIntent, 0)
        shortcutManager.requestPinShortcut(shortcut, successCallback.intentSender)
    }
}

Flutter调用Kotlin代码:

import 'package:flutter/services.dart';

const platform = const MethodChannel('com.example.shortcuts/shortcut');

Future<void> createShortcut(String appName, int iconResId, String intentAction) async {
  try {
    await platform.invokeMethod('createShortcut', {
      'appName': appName,
      'iconResId': iconResId,
      'intentAction': intentAction,
    });
  } on PlatformException catch (e) {
    print("Failed to create shortcut: ${e.message}");
  }
}
  1. 检查是否生成App桌面快捷方式

Kotlin代码:

fun isShortcutCreated(context: Context, appName: String): Boolean {
    val shortcutManager = context.getSystemService(ShortcutManager::class.java)
    val shortcuts = shortcutManager!!.dynamicShortcuts
    for (shortcut in shortcuts) {
        if (shortcut.id == appName) {
            return true
        }
    }
    return false
}

Flutter调用Kotlin代码:

import 'package:flutter/services.dart';

const platform = const MethodChannel('com.example.shortcuts/shortcut');

Future<bool> isShortcutCreated(String appName) async {
  try {
    final bool isCreated = await platform.invokeMethod('isShortcutCreated', {
      'appName': appName,
    });
    return isCreated;
  } on PlatformException catch (e) {
    print("Failed to check shortcut: ${e.message}");
    return false;
  }
}

导入包:

import android.content.Context
import android.content.Intent
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.content.pm.ShortcutInfoCompat
import androidx.core.content.pm.ShortcutManagerCompat
import androidx.core.graphics.drawable.IconCompat
import 'package:flutter/services.dart';
``
flutter调用用kotlin编写的检查是否生成App桌面快捷方式代码和自动生成APP桌面快捷方式代码按照以上要求请提供完整代码以及导入包

原文地址: https://www.cveoy.top/t/topic/eojw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录