在 Android 12 中,您可以使用 ShortcutManager 类创建桌面快捷方式。以下是一个完整的代码示例,演示如何在点击按钮时创建快捷方式:\n\njava\nimport android.content.Intent;\nimport android.graphics.drawable.Icon;\nimport android.os.Bundle;\nimport android.os.PersistableBundle;\nimport android.view.View;\nimport android.widget.Button;\n\nimport androidx.appcompat.app.AppCompatActivity;\n\npublic class MainActivity extends AppCompatActivity {\n\n private Button createShortcutButton;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n\n createShortcutButton = findViewById(R.id.create_shortcut_button);\n createShortcutButton.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n createShortcut();\n }\n });\n }\n\n private void createShortcut() {\n Intent shortcutIntent = new Intent(getApplicationContext(), MainActivity.class);\n shortcutIntent.setAction(Intent.ACTION_MAIN);\n\n ShortcutInfo shortcutInfo = new ShortcutInfo.Builder(getApplicationContext(), "shortcut_id")\n .setIntent(shortcutIntent)\n .setShortLabel("Shortcut")\n .setIcon(Icon.createWithResource(getApplicationContext(), R.drawable.ic_shortcut))\n .build();\n\n ShortcutManager shortcutManager = getSystemService(ShortcutManager.class);\n shortcutManager.setDynamicShortcuts(Arrays.asList(shortcutInfo));\n }\n}\n\n\n首先,在AndroidManifest.xml文件中添加以下权限:\n\nxml\n<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />\n\n\n然后,在res目录下创建xml文件夹,并在其中创建shortcuts.xml文件,添加以下内容:\n\nxml\n<shortcuts xmlns:android="http://schemas.android.com/apk/res/android">\n <shortcut\n android:shortcutId="shortcut_id"\n android:enabled="true"\n android:icon="@drawable/ic_shortcut"\n android:shortcutShortLabel="@string/shortcut_label"\n android:shortcutLongLabel="@string/shortcut_label">\n <intent\n android:action="android.intent.action.MAIN"\n android:targetPackage="com.example.myapplication"\n android:targetClass="com.example.myapplication.MainActivity" />\n <categories android:name="android.shortcut.conversation" />\n </shortcut>\n</shortcuts>\n\n\n最后,在res目录下创建drawable文件夹,并添加ic_shortcut.png作为快捷方式图标。\n\n请注意,你需要将com.example.myapplication替换为你的应用程序的包名。\n\n以上代码会在点击按钮时创建一个名为"Shortcut"的快捷方式,并将其添加到桌面。


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

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