遇到一个以前不知道的东西,activity-alias所以记录一下。
我们可以通过activity-alias来实现动态修改APP图标的功能。
首先,需要在AndroidManifest.xml文件中声明activity-alias,方法如下:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.qm.myapplication">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".LoginActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity-alias
android:name=".test1"
android:enabled="false"
android:icon="@mipmap/base_app_icon"
android:targetActivity=".LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity-alias>
</application>
</manifest>
activity-alias标签的android:name属性是别名,代表一个activity的入口的副本。我们可以利用这个特性将APP入口复制多份。android:enabled属性代表activity-alias是否启用,要是有多个activity-alias同时启用的话,会在桌面上出现多个图标,所以这块我把他设置成了false。android:icon是我们实现动态修改APP桌面图标的重点,它会设置Activity的ICON如果我们设置的Activity是APP的入口这个就是我们APP的ICON了。android:targetActivity属性代表我们要关联的Activity。之后和activity标签一样要设置一下intent-filter,好了配置文件就大功告成了。_
下面看一下Activity的实现:
public class LoginActivity extends AppCompatActivity {
private ComponentName mComponentName;
private ComponentName mComponentNameDefault;
private PackageManager mPackageManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//获取我们设置的别名组件
mComponentName = new ComponentName(getBaseContext(), getPackageName() + ".test1");
//获取默认组件
mComponentNameDefault = new ComponentName(getBaseContext(), getPackageName() + ".LoginActivity");
//获取PackageManager
mPackageManager = getApplication().getPackageManager();
}
public void onBtnClick(View v) {
//判断现在显示的是哪个组件,组件未启用或者是默认情况启用别名组件
if (mPackageManager.getComponentEnabledSetting(mComponentName) == PackageManager.COMPONENT_ENABLED_STATE_DISABLED || mPackageManager.getComponentEnabledSetting(mComponentName) == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT) {
mPackageManager.setComponentEnabledSetting(mComponentName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
mPackageManager.setComponentEnabledSetting(mComponentNameDefault, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
} else if (mPackageManager.getComponentEnabledSetting(mComponentName) == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
mPackageManager.setComponentEnabledSetting(mComponentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
mPackageManager.setComponentEnabledSetting(mComponentNameDefault, PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
}
}
}
(@ο@) 哇~,大功告成!现在就可以切换桌面图标了。