你好,游客 登录 注册 搜索
背景:
阅读新闻

简单分析Android中添加shortcut方面的源码

[日期:2012-08-12] 来源:Linux社区  作者:zircon_1973 [字体:大 中 小]
它推荐使用activity-alias来提供CREATE_SHORTCUT这个IntentFilter,这样可以通过label和icon属性来自定义picker那个activity中显示这个shortcut的名称和图标,<action Android:name="android.intent.action.CREATE_SHORTCUT" />分析在上面第二步。回到这个activity中,在setupShortcut()方法中,设置了上面第三步中所描述Intent,这个activity同时是那个当点击shortcut时所指向的那个具体功能的activity,所以intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent)指向了自己。最后别忘了:
  1. setResult(RESULT_OK, intent);  
通过其返回到Launcher中。

有时我们会看到有些应用一安装完就在桌面添加了一个shortcut或是程序中可以点击一下按钮就在桌面创建一个shortcut,这时我们要用到Launcher中的一个广播接收者,在Launcher的manifest文件中:

  1. <receiver  
  2.             android:name="com.android.launcher2.InstallShortcutReceiver"  
  3.             android:permission="com.android.launcher.permission.INSTALL_SHORTCUT">  
  4.             <intent-filter>  
  5.                 <action android:name="com.android.launcher.action.INSTALL_SHORTCUT" />  
  6.             </intent-filter>  
  7. </receiver>  
大家可以去看下这个广播接收者的源码。
下面通过一个例子来说明下用法:通过点击一个按钮在桌面创建一个shortcut。

TestCreateShortcut.java

  1. public class TestCreateShortcut extends Activity {  
  2.     @Override  
  3.     protected void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         setContentView(R.layout.test_shortcut);  
  6.         Button button = (Button) findViewById(R.id.install);  
  7.         button.setOnClickListener(new OnClickListener() {  
  8.             @Override  
  9.             public void onClick(View v) {  
  10.                 Intent intent = new Intent();  
  11.                 //install_shortcut action   
  12.                 intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");  
  13.                 //点击shortcut时进入的activity,这里是自己   
  14.                 intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(  
  15.                         TestCreateShortcut.this, TestCreateShortcut.class));  
  16.                 //shortcut的name   
  17.                 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "MyShortcut");  
  18.                 Parcelable iconResource = Intent.ShortcutIconResource  
  19.                         .fromContext(TestCreateShortcut.this, R.drawable.icon);  
  20.                 //shortcut的icon   
  21.                 intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,  
  22.                         iconResource);  
  23.                 //是否可以重复放置shortcut,默认true   
  24.                 intent.putExtra("duplicate", false);  
  25.                 sendBroadcast(intent);  
  26.             }  
  27.         });  
  28.     }  
  29. }  
还有别忘了在你的manifest文件中加上这个权限:
  1. <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/>  
OK.linux
相关资讯       Android开发基础教程 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款