写在20111010:添加快捷方式到桌面

1.应用自身启动时创建快捷方式
   当我们在模拟器或手机上屏幕上长按屏幕会弹出选择框,询问是否添加快捷方式等操作:当我们选择ShortCut后,就会出现一个ListView列出所有可以添加的items:
下面通过手动建立一个程序,添加了intentFilter为android.intent.action.CREATE_SHORTCUT的intent,这样当选择了它后,就会在桌面生成一个自定义需要这个activity去做一件事情的快捷图标:
处理点击快捷图标后执行的代码块Shortcut.java
Intent addShortcut;  
//获取启动这个activity的intent的action  
if (getIntent().getAction().equals(Intent.ACTION_CREATE_SHORTCUT)) {  
    addShortcut = new Intent();  
    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, "110");  
    Parcelable icon = Intent.ShortcutIconResource.fromContext(this,   R.drawable.icon);  
    //初始化快捷方式图标  
    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,icon);  
    Intent callPolice = new Intent(Intent.ACTION_CALL, Uri  
                  .parse("tel://110"));                    
    addShortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, callPolice);  
    setResult(RESULT_OK, addShortcut);  
} else {  
    setResult(RESULT_CANCELED);  
}  
    finish();  
第二个主要的是配置文件AndroidMenifest.xml文件
<activity android:name=".Shortcut">  
<intent-filter>  
   <action android:name="android.intent.action.CREATE_SHORTCUT" />    </intent-filter>  
          
   这样当手长按时弹出的快捷方式中,点击该应用时发送一个这样的Intent,其ACTION为android.intent.action.CREATE_SHORTCUT,就会在桌面建立一个拨打110的快捷方式。
2.发送广播方式让Launcher创建快捷方式
  主要是通过一个按钮点击事件广播一个intent给所有可能接收到的Receivers来响应,
public void shortcutCreate() {  
    Intent intent = new Intent(ACTION_ADD_SHORTCUT);  
    Intent dial = new Intent(Intent.ACTION_CALL);  
    dial.setData(Uri.parse("tel://110"));  
    intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "dial to 110");  
    intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, dial);  
    intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,  
    Intent.ShortcutIconResource.fromContext(this, R.drawable.jing));  
    sendBroadcast(intent);  

2.配置文件AndroidMenifest.xml文件
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />  
三、判断是否已经创建了快捷方式
private boolean hasShortcut()

    boolean isInstallShortcut = false;
    final ContentResolver cr = mapViewActivity.getContentResolver();
    final String AUTHORITY ="com.android.launcher.settings";
    final Uri CONTENT_URI = Uri.parse("content://" +AUTHORITY  + "/favorites?notify=true");
    Cursor c = cr.query(CONTENT_URI,new String[] {"title","iconResource" },"title=?",
    new String[] {mapViewActivity.getString(R.string.app_name).trim()}, null);
    if(c!=null && c.getCount()>0){
        isInstallShortcut = true ;
    }
   return isInstallShortcut ;
}

猜你喜欢

转载自meohao.iteye.com/blog/1909140