创建桌面快捷方式
快捷方式的创建,需要注意两点:
1.创建快捷方式的权限. 2.只能创建一次快捷键 3.写环保代码(代码中有说明)
/** * 创建快捷键 */ public class MainActivity extends AppCompatActivity { private SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sharedPreferences = getSharedPreferences("config", MODE_PRIVATE); installShortCut();//创建快捷方式 } /** * 创建快捷键图标,注意:这里有一个发送广播的意图和携带数据的意图,该方法只会创建一次快捷方式 * 切记要加权限: <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/> */ private void installShortCut(){ boolean values = sharedPreferences.getBoolean("要创建快捷方式吗", true);//第一次创建 if(values){ SharedPreferences.Editor edit = sharedPreferences.edit(); edit.putBoolean("要创建快捷方式吗", false);//下次就不会执行这段代码创建快捷方式了 edit.commit(); //发送广播的意图,告诉桌面要创建快捷图标 Intent intent=new Intent(); intent.setAction("com.android.launcher.action.INSTALL_SHORTCUT"); //快捷方式要包含3个重要的信息,1.名称 2.图标 3.干什么事情 intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,"显示在桌面的名称"); intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher)); //指定点击桌面快捷图标要开启的Activity /* 方式一:如果是这样设置,删除应用的时候,快捷图标不会被跟着删除,所以不是环保代码 Intent shortcutIntent=new Intent(this,MainActivity.class);*/ Intent shortcutIntent=new Intent(); //这中设置方式才是环保应用,删除应用的时候,快捷方式也会跟着被删除 shortcutIntent.setAction("android.intent.action.MAIN"); shortcutIntent.addCategory("android.intent.category.LAUNCHER"); shortcutIntent.setClassName(getPackageName(),"com.ts.test.MainActivity");//指定包名和类名 //将这个参数intent发给广播接收者 intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,shortcutIntent); sendBroadcast(intent); } } }
清单信息
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.ts.test"> <!--创建快捷方式的权限,和广播中的Action值差不多--> <uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>