packagecom.zhy.shortcut;importandroid.app.Activity;importandroid.content.ComponentName;importandroid.content.Intent;importandroid.content.SharedPreferences;importandroid.content.SharedPreferences.Editor;importandroid.os.Bundle;importandroid.preference.PreferenceManager;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;publicclassShortCutActivityextendsActivity {privatestaticfinalString CREATE_SHORTCUT_ACTION="com.android.launcher.action.INSTALL_SHORTCUT";privatestaticfinalString DROP_SHORTCUT_ACTION="com.android.launcher.action.UNINSTALL_SHORTCUT";privatestaticfinalString PREFERENCE_KEY_SHORTCUT_EXISTS="IsShortCutExists";
Button button;//获取默认的SharedPreferencesSharedPreferences sharedPreferences ;//从SharedPreferences获取是否存在快捷方式 若不存在返回false 程序第一次进来肯定返回falsebooleanexists ;
@OverridepublicvoidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
sharedPreferences=PreferenceManager.getDefaultSharedPreferences(this);
exists=sharedPreferences.getBoolean(PREFERENCE_KEY_SHORTCUT_EXISTS,false);//创建桌面快捷方式//若第一次启动则创建,下次启动则不创建if(!exists) {
setUpShortCut();
}
setContentView(R.layout.main);
button=(Button) findViewById(R.id.dropShortCut);
button.setOnClickListener(newOnClickListener() {
@OverridepublicvoidonClick(View v) {
tearDownShortCut();
}
});
}/*** 创建桌面快捷方式*/privatevoidsetUpShortCut() {
Intent intent=newIntent(CREATE_SHORTCUT_ACTION);//设置快捷方式图片intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,Intent.ShortcutIconResource.fromContext(this, R.drawable.logo));//设置快捷方式名称intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"sina");//设置是否允许重复创建快捷方式 false表示不允许intent.putExtra("duplicate",false);//设置快捷方式要打开的intent//第一种方法创建快捷方式要打开的目标intentIntent targetIntent=newIntent();//设置应用程序卸载时同时也删除桌面快捷方式targetIntent.setAction(Intent.ACTION_MAIN);
targetIntent.addCategory("android.intent.category.LAUNCHER");
ComponentName componentName=newComponentName(getPackageName(),this.getClass().getName());
targetIntent.setComponent(componentName);//第二种方法创建快捷方式要打开的目标intent/** Intent
* targetIntent=getPackageManager().getLaunchIntentForPackage(getPackageName
* ());*/intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, targetIntent);//发送广播sendBroadcast(intent);
Editor editor=sharedPreferences.edit();
editor.putBoolean(PREFERENCE_KEY_SHORTCUT_EXISTS,true);
editor.commit();
}/*** 删除桌面快捷方式*/privatevoidtearDownShortCut() {
Intent intent=newIntent(DROP_SHORTCUT_ACTION);//指定要删除的shortcut名称intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"sina");
String appClass=getPackageName()+"."+this.getLocalClassName();
ComponentName component=newComponentName(getPackageName(), appClass);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,newIntent().setAction(Intent.ACTION_MAIN).setComponent(component));
sendBroadcast(intent);
}
}