android创建桌面快捷方式

本文详细介绍了在Android系统中创建桌面快捷方式的方法,包括所需权限、实现步骤及关键代码示例,并强调了确保快捷方式正常启动目标Activity的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前安卓创建桌面快捷方式的时候,会出现点击快捷方式无法出现我们想要的activity的情况。

在这里对创建快捷方式做一个总结,创建快捷方式必须添加权限:

权限

<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

创建快捷方式的ShortCut.class:


public class ShortCut {
    public String ACTION_ADD_SHORTCUT = "com.android.launcher.action.INSTALL_SHORTCUT";
    private Context mContext;
    public ShortCut(Context c){
        mContext = c;
    }

    public void createShortCut(){
        Intent createShortcutIntent = new Intent(ACTION_ADD_SHORTCUT);
        // 不允许重复创建快捷方式
        createShortcutIntent.putExtra("duplicate", false);
        // 名称
        createShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mContext.getString(R.string.short_cut_name));
        // 图标
        createShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(mContext,R.mipmap.ic_launcher));
        // 设置要启动的activity
        Intent launcherIntent = new Intent(Intent.ACTION_MAIN);
        launcherIntent.setClass(mContext, AppActivity.class);
        launcherIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        //这句防止唤醒的activity被遮挡
        launcherIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        createShortcutIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, launcherIntent);
        // 发送广播
        mContext.sendBroadcast(createShortcutIntent);
    }
}

引用createShortCut方法:


public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ShortCut shortCut = new ShortCut(getBaseContext());
        shortCut.createShortCut();
    }
}


接下来是最重要的一点:

在AndroidManifest.xml中,必须对快捷方式要启动的activity添加:


  <activity android:name=".AppActivity">
            <intent-filter>
                <action android:name="cn.kuwo.player.action.SHORTCUT"/>
                <category android:name="android.intent.category.DEFAULT" /> 
            </intent-filter>
        </activity>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值