国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > 互联网 > Android-Launcher开发之ShortCut(1)

Android-Launcher开发之ShortCut(1)

来源:程序员人生   发布时间:2014-09-05 19:02:47 阅读次数:2173次

以下源码来自Launcher2.3的例子

1.默认每个应用的主Activity都会自带 <category android:name="android.intent.category.LAUNCHER" />,表示该应用安装到Launcher时点击打开该Activity

<activity android:name="org.lean.MainActivity" android:label="@string/app_name" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>

2.Launcher2源码的时序图如下:(在图中,我们可以看到 创建shortcut需要准备2方面东西,一个action.,另一个是我们检索后返回的intent)



2.1.当想在桌面手动创建shortcut,就必须在AndroidManifest.xml文件中添加一个<action />标签.

如下.我们创建一个ShortCutActivity用来处理shortcut的创建

<activity android:name="org.lean.ShortCutActivity" > <intent-filter > <action android:name="android.intent.action.CREATE_SHORTCUT" /> </intent-filter> </activity>

2.2并在Activity中处理显示的shortCut样式的返回Intent

/** * @author Lean @date:2014-8-25 */ public class ShortCutActivity extends Activity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) { Intent returnIntent=new Intent(); returnIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this,R.drawable.ic_launcher)); returnIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"A simple shortCut"); returnIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent(this,MainActivity.class)); setResult(RESULT_OK,returnIntent); finish(); } } }

3.以上的shortcut只能手动添加,如果想动态添加shortCut 就必须发送广播.Android Launcher2源码提供了如下

<!-- Intent received used to install shortcuts from other applications --> <receiver android:name="com.android.launcher2.InstallShortcutReceiver" android:permission="com.android.launcher.permission.INSTALL_SHORTCUT"> <intent-filter> <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" /> </intent-filter> </receiver>

这也表示,我们发送广播必须声明权限,还有指定<action />,于是 在我们的应用程序AndroidManifest.xml里 添加

<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />

同时在代码调用(同时,动态添加shortcut也必须指定其样式和操作意图)

Intent intent=new Intent(); intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,R.drawable.ic_launcher); intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"a auto sample"); intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,new Intent(MainActivity.this,MainActivity.class)); sendBroadcast(intent);






生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生