之前安卓创建桌面快捷方式的时候,会出现点击快捷方式无法出现我们想要的activity的情况。
在这里对创建快捷方式做一个总结,创建快捷方式必须添加权限:
权限
<!-- 添加快捷方式 -->
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<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>