Android桌面快捷方式


Android中的桌面快捷方式和PC机上的快捷方式一样,用于启动某一应用程序。要在桌面添加一个快捷方式非常简单,只需长按桌面或者点击"Menu"按钮,然后在弹出的选项中选择shortcut,然后选择要添加的快捷方式即可。

下面主要介绍如何通过代码将一个应用程序添加到桌面快捷方式。

首先在描述文件AndroidManifest.xml中注册一个action为:<action android:name="android.intent.action.CREATE_SHORTCUT"/>

如下所示:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       package="com.test.shortcut"  
  4.       android:versionCode="1"  
  5.       android:versionName="1.0">  
  6.   
  7.   
  8.     <application android:icon="@drawable/icon" android:label="@string/app_name">  
  9.         <activity android:name=".MainActivity"  
  10.                   android:label="@string/app_name">  
  11.             <intent-filter>  
  12.                 <action android:name="android.intent.action.MAIN" />  
  13.                 <category android:name="android.intent.category.LAUNCHER" />  
  14.                 <action android:name="android.intent.action.CREATE_SHORTCUT"/>  
  15.             </intent-filter>  
  16.         </activity>  
  17.     </application>  
  18. </manifest>  
接下来是MainActivity:
  1. public class MainActivity extends Activity {  
  2.     /** Called when the activity is first created. */  
  3.     @Override  
  4.     public void onCreate(Bundle savedInstanceState) {  
  5.         super.onCreate(savedInstanceState);  
  6.         setContentView(R.layout.main);  
  7.           
  8.         Intent intent;  
  9.         //判断是否要添加快捷方式   
  10.         if (this.getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)){  
  11.             intent = new Intent();  
  12.             //设置快捷方式名称   
  13.             intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "拨打电话");  
  14.               
  15.             //设置快捷方式图标   
  16.             Parcelable icon = Intent.ShortcutIconResource.fromContext(this, android.R.drawable.stat_sys_phone_call);  
  17.             intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);  
  18.               
  19.             //设置快捷方式执行的intent   
  20.             Uri uri = Uri.parse("tel:055555");    
  21.             Intent it = new Intent(Intent.ACTION_DIAL, uri);    
  22.             intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, it);  
  23.               
  24.             setResult(RESULT_OK,intent);  
  25.         }else {  
  26.             //取消   
  27.             setResult(RESULT_CANCELED);;  
  28.         }  
  29.         this.finish();  
  30.     }  
  31. }  

代码非常简单,运行程序,长按桌面,选择shortcut后如图所示:


选择将ShortCut添加到桌面,效果如图:


单击“拨打电话”图标,出现如图所示结果:


更多Android相关信息见Android 专题页面 http://www.bkjia.com/topicnews.aspx?tid=11

相关内容