android程序桌面快捷方式的檢測添加和刪除


廢話不多說了,可能好多同志都在找這個功能的實現代碼。下面就由我來講講吧!

我的添加和刪除快捷方式是在登陸的時候由用戶選擇的,效果是一個CheckBox,初始化界面的時候會查看用戶以前是否已經勾選,再給他添加偵聽,就能分別添加和刪除快捷方式了。

代碼如下:

        saveShortcuts=(CheckBox) findViewById(R.id.saveshortcut);
        saveShortcuts.setOnCheckedChangeListener(clistener);

 監聽並獲取動作

private OnCheckedChangeListener clistener= new OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      if(buttonView.getId()==R.id.saveshortcut){
   sp=getSharedPreferences(PREFERENCE_NAME, Activity.MODE_PRIVATE);//獲取系統內保存的用戶文件
    sp.edit().putBoolean("saveshortcuts", isChecked).commit();//將用戶的選擇保存到系統
    if(isChecked&&!hasShortcut()){//如果被選擇,就執行檢測和創建快捷方式
addShortcut();
}else if(!isChecked&&hasShortcut()){//否則就監測和刪掉快捷方式
delShortcut();
}
}
}
};

 

處理動作:判斷

 //檢測是否存在快捷方式
private boolean hasShortcut()
{
boolean isInstallShortcut = false;
final ContentResolver cr = getContentResolver();
//2.2版本的是launcher2,不然無效,網上有的是launcher,我試驗了2.2不能用
final Uri CONTENT_URI = Uri.parse("content://com.android.launcher2.settings/favorites?notify=true");//保持默認
Cursor c = cr.query(CONTENT_URI,new String[] {"title","iconResource" },"title=?", //保持默認
//getString(R.string.app_name)是獲取string配置文件中的程序名字,這里用一個String的字符串也可以
new String[] {getString(R.string.app_name).trim()}, null);
if(c!=null && c.getCount()>0){
isInstallShortcut = true ;
}
return isInstallShortcut ;
}

下面就是添加快捷方式了:

    //創建快捷方式
private void addShortcut(){
Intent shortcut = new Intent("com.android.launcher.action.INSTALL_SHORTCUT");//保持默認
//快捷方式的名稱
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name)); //保持默認
shortcut.putExtra("duplicate", false); //不允許重復創建
Intent intent = new Intent(this,logo.class);//后面的logo.class是我的程序第一次加載的activity的名字,大家要注意
intent.setAction("com.hooypay.Activity.logo");//這個也是logo的具體路徑
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
//顯示的圖標
Parcelable icon = Intent.ShortcutIconResource.fromContext(this,R.drawable.ic_launcher);
shortcut.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, icon);
sendBroadcast(shortcut);//廣播
}

最后是刪除快捷方式:

//刪除快捷方式
private void delShortcut(){
Intent shortcut = new Intent("com.android.launcher.action.UNINSTALL_SHORTCUT");
//快捷方式的名稱
shortcut.putExtra(Intent.EXTRA_SHORTCUT_NAME, getString(R.string.app_name));

//這里的intent要和創建時的intent設置一致
Intent intent = new Intent(this,logo.class);
intent.setAction("com.hooypay.Activity.logo");
shortcut.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
sendBroadcast(shortcut);
}


以上是在參考網上的資料編寫的。本人技術拙陋,如有錯誤,希望大家指正,謝謝


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM