【Android】动态更新Icon

动态更改图标主要用到activity-aliasPackageManager的setComponentEnabledSetting方法。具体步骤如下:

1、在AndroidManifest.xml中增加以下声明:


        
            

            
        

完整文件如下:




    
        
            
                

                
            
        
        
            
                

                
            
        
    


2、切换图标

getPackageManager().setComponentEnabledSetting(getComponentName(),
            PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
            PackageManager.DONT_KILL_APP);
getPackageManager().setComponentEnabledSetting(new ComponentName(this,
                    getPackageName() + ".alias"),
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
            0);

setComponentEnabledSetting方法的最后一个参数,PackageManager.DONT_KILL_APP表示不关闭App,0表示关闭App刷新图标。

完整文件如下:

package com.wangyz.dynamicicon;

import android.content.ComponentName;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void changeIcon(View view) {
        getPackageManager().setComponentEnabledSetting(getComponentName(),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        getPackageManager().setComponentEnabledSetting(new ComponentName(this,
                        getPackageName() + ".MainActivity"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                0);
    }

    public void changeIconAlias(View view) {
        getPackageManager().setComponentEnabledSetting(getComponentName(),
                PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        getPackageManager().setComponentEnabledSetting(new ComponentName(this,
                        getPackageName() + ".alias"),
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                0);
    }
}

源码地址:https://github.com/milovetingting/Samples/tree/master/DynamicIcon

你可能感兴趣的:(【Android】动态更新Icon)