Android-Launcher开发之ShortCut(1)

下面源代码来自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);






原文地址:https://www.cnblogs.com/mfrbuaa/p/4319066.html