项目开发过程中,后台的接口域名可能会分生产环境和测试环境,生产环境是app正式环境,测试环境是开发过程中使用的环境,接口中有假数据,供我们开发人员使用。在开发过程中有这样一种情况会出现,我们需要生产和测试环境切换来排查问题,常规做法,就需要更改接口域名地址,然后重新编译运行app,那我们可不可以在app运行中直接切换环境呢?
答案是可以的。
步骤1:
在app目录下新建configs目录,configs目录新建auto和release目录。
auto:开发版本使用的配置文件。
release:线上产品版本使用的配置文件。

先看auto目录下的文件,每个文件代表一种环境,这几个环境都可以相互切换。
config.properties:默认环境
# 默认使用环境 为 测试环境test
#环境名
name=test
#url
api.base.url=http://apitest.toohotdhc.com/
#是否为线上
isProduct=false
configTest.properties:测试环境
# 测试环境
#环境名
name=test
#url
api.base.url=http://apitest.toohotdhc.com/
#是否为线上
isProduct=false
configPre.properties:预发布环境
# 预发布环境
#环境名
name=pre
#url
api.base.url=http://apipre.toohotdhc.com
#是否为线上
isProduct=false
configProduct.properties:正式环境
# 正式环境    
#环境名
name=product
#url
api.base.url=http://api.toohotdhc.com
#是否为线上
isProduct=true
release目录下只有一个文件,代表线上产品版本,这个是不能切换环境的,这个是要真正上线给用户使用的,肯定是不能切换环境的。
config.properties:线上环境
# 线上环境  
#环境名
name=product
#url
api.base.url=http://api.toohotdhc.com
#是否为线上
isProduct=true
步骤2:配置build.gradle
plugins {
    id 'com.android.application'
}
android {
    compileSdkVersion 30
    buildToolsVersion "30.0.2"
    defaultConfig {
        applicationId "com.zly.environmemtconfig"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        // 多渠道打包,AS3.0之后:原因就是使用了productFlavors分包,解决方法就是在build.gradle中的defaultConfig中
        // 添加一个flavorDimensions "1"就可以了,后面的1一般是跟你的versionCode相同
        flavorDimensions "1"
        buildConfigField("boolean", "IS_PRODUCT", "false")
    }
    signingConfigs {
        release {
            storeFile file("../yipingcankey.jks")
            keyAlias '上海'
            keyPassword '88888888'
            storePassword '88888888'
        }
    }
    buildTypes {
        debug {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
        release {
            minifyEnabled false
            signingConfig signingConfigs.release
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    sourceSets {
        //开发版本使用的配置文件
        auto {
            assets.srcDirs = ['assets', 'configs/auto']
        }
        // 线上产品版本使用的配置文件
        product {
            assets.srcDirs = ['assets', 'configs/release']
        }
    }
    //多渠道打包
    productFlavors {
        // 开发版本
        auto {
            //可以设置app不同环境的名字
            manifestPlaceholders = [app_name: "支付宝-Auto"]
        }
        // 线上产品版本
        product {
            buildConfigField('boolean', 'IS_PRODUCT', "true")
            manifestPlaceholders = [app_name: "支付宝"]
        }
    }
    applicationVariants.all { variant ->
        variant.outputs.all { output ->
            def buildTypeName = variant.buildType.name
            def versionName = defaultConfig.versionName
            // 多渠道打包的时候,后台不支持中文
            outputFileName = "appName-v${versionName}-${buildTypeName}-${buildTime()}.apk"
        }
    }
}
static def buildTime() {
    def date = new Date()
    def formattedDate = date.format('MMddHHmmss')
    return formattedDate
}
dependencies {
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    testImplementation 'junit:junit:4.+'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}
//设置默认环境:不写参数或者环境名错误,则默认test
setDefaultEnv()
def setDefaultEnv() {
    def envName = envConfig()
    def envConfigDir = "${rootDir}/app/configs/auto/"
    //def envConfigDir = "${rootDir}/app/configs/release/"
    def renameFile = "config.properties"
    println("打包接口环境:${envName}")
    task configCopy(type: Copy) {
        copy {
            delete "${envConfigDir}/${renameFile}"
            from(envConfigDir)
            into(envConfigDir)
            include(envName)
            rename(envName, renameFile)
        }
    }
}
String envConfig() {
    def envName = "test"  //默认环境
    if (hasProperty("env")) {
        envName = getPropmerty("env")
    }
    println("参数为:${envName}")
    def envFileName = 'configTest'
    if (envName == "test")
        envFileName = 'configTest'
    else if (envName == "pre")
        envFileName = 'configPre'
    else if (envName == "product")
        envFileName = 'configProduct'
    return envFileName + ".properties"
}
步骤3:Manifese文件配置渠道包的app名字
  <application
        android:name=".AppApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="${app_name}"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.EnvironmemtConfig">
步骤4:初始化环境配置
AppApplication
public class AppApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        SpUtils.init(this);
        PropertyUtils.init(this); //加载环境配置文件
    }
}
PropertyUtils:加载配置文件工具类
public class PropertyUtils {
    private static Properties mProps = new Properties();
    private static boolean mHasLoadProps = false;
    private static final Object mLock = new Object();
    private static final String TAG = "PropertyUtils";
    public PropertyUtils() {
    }
    /**
     * 在AppApplication中初始化
     */
    public static void init(Context context) {
        if (!mHasLoadProps) {
            synchronized (mLock) {
                if (!mHasLoadProps) {
                    try {
                        //获取环境类型
                        ConfigManager.EnvironmentType environmentType = ConfigManager.getDefault().getAppEnv();
                        //Log.e("xyh", "init: " + environmentType.configType + ".properties");
                        InputStream is = context.getAssets().open(environmentType.configType + ".properties");
                        mProps.load(is);
                        mHasLoadProps = true;
                        Log.e(TAG, "load config.properties successfully!");
                    } catch (IOException var4) {
                        Log.e(TAG, "load config.properties error!", var4);
                    }
                }
            }
        }
    }
    public static String getApiBaseUrl() {
        if (mProps == null) {
            throw new IllegalArgumentException("must call #UtilsManager.init(context) in application");
        } else {
            return mProps.getProperty(PropertyKey.BASE_URL, "");
        }
    }
    public static boolean isProduct() {
        return mProps.getProperty(PropertyKey.IS_PRODUCT, "false").equals("true");
    }
    public static String getEnvironmentName() {
        return mProps.getProperty(PropertyKey.NAME, "");
    }
    public static ConfigManager.EnvironmentType environmentMap() {
        String envName = getEnvironmentName();
        switch (envName) {
            case "test":
                return ConfigManager.EnvironmentType.TEST;
            case "pre":
                return ConfigManager.EnvironmentType.PRE;
            case "product":
                return ConfigManager.EnvironmentType.PRODUCT;
            default:
                return ConfigManager.EnvironmentType.DEFAULT;
        }
    }
}
ConfigManager:环境配置管理类
/**
 * 环境配置管理类
 */
public class ConfigManager {
    //当前环境
    private EnvironmentType mCurrentEnvType;
    private static final String APP_ENV = "appEnv";
    private ConfigManager() {
    }
    public static ConfigManager getDefault() {
        return HOLDER.INSTANCE;
    }
    private static class HOLDER {
        static ConfigManager INSTANCE = new ConfigManager();
    }
    /***
     * 保存环境:指在切换环境时调用一次
     */
    public void saveAppEnv(EnvironmentType type) {
        SpUtils.putString(APP_ENV, type.configType);
    }
    /***
     * 获取环境类型
     */
    public EnvironmentType getAppEnv() {
        if (mCurrentEnvType == null) {
           // Log.e("xyh", "FLAVOR: " + BuildConfig.FLAVOR);
            String env;
            if (Constants.AUTO.equals(BuildConfig.FLAVOR)) {
                env = SpUtils.getString(APP_ENV, EnvironmentType.DEFAULT.configType);
                if (TextUtils.isEmpty(env)) {
                    env = EnvironmentType.DEFAULT.configType;
                }
            } else {
                env = EnvironmentType.DEFAULT.configType;
            }
            mCurrentEnvType = EnvironmentType.map(env);
        }
        return mCurrentEnvType;
    }
    //环境类型
    public enum EnvironmentType {
        /***
         * 默认环境   config:环境配置文件名
         */
        DEFAULT("config"),
        /***
         * test环境
         */
        TEST("configTest"),
        /***
         * 预发布环境
         */
        PRE("configPre"),
        /***
         * 线上环境
         */
        PRODUCT("configProduct");
        String configType;
        EnvironmentType(String configType) {
            this.configType = configType;
        }
        public static EnvironmentType map(String configType) {
            if (TextUtils.equals(EnvironmentType.TEST.configType, configType)) {
                return EnvironmentType.TEST;
            } else if (TextUtils.equals(EnvironmentType.PRE.configType, configType)) {
                return EnvironmentType.PRE;
            } else if (TextUtils.equals(EnvironmentType.PRODUCT.configType, configType)) {
                return EnvironmentType.PRODUCT;
            } else {
                return EnvironmentType.DEFAULT;
            }
        }
    }
}
PropertyKey :配置文件相关属性
@StringDef({PropertyKey.BASE_URL, PropertyKey.IS_PRODUCT, PropertyKey.NAME})
@Retention(RetentionPolicy.SOURCE)
public @interface PropertyKey {
    String NAME = "name";
    String BASE_URL = "api.base.url";
    String IS_PRODUCT = "isProduct";
}
Constants :常量类
public class Constants {
    public static final String AUTO="auto";
}
步骤5:切换环境
public class MainActivity extends AppCompatActivity {
    private Button mBtnSwitchEnv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mBtnSwitchEnv = (Button) findViewById(R.id.btn_switch_env);
        Log.e("xyh", "getEnvironmentName: " + PropertyUtils.getEnvironmentName());
        Log.e("xyh", "getApiBaseUrl: " + PropertyUtils.getApiBaseUrl());
        Log.e("xyh", "isProduct: " + PropertyUtils.isProduct());
        //开发版本才可以切换环境
        if (Constants.AUTO.equals(BuildConfig.FLAVOR)) {
            mBtnSwitchEnv.setOnClickListener(v -> {
                startActivity(new Intent(this, UrlEnvironmentActivity.class));
            });
        }
    }
}
UrlEnvironmentActivity:切换环境页面
public class UrlEnvironmentActivity extends AppCompatActivity {
    private TextView mTvEnvShow;
    private RadioGroup mRadioGroup;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_url_environment);
        mTvEnvShow = (TextView) findViewById(R.id.tvEnvShow);
        mRadioGroup = (RadioGroup) findViewById(R.id.group);
        mTvEnvShow.setText("环境:" + PropertyUtils.getEnvironmentName() + "\n" +
                "url:" + PropertyUtils.getApiBaseUrl());
        ConfigManager.EnvironmentType environmentType = PropertyUtils.environmentMap();
        switch (environmentType) {
            case TEST:
                mRadioGroup.check(R.id.rb_test);
                break;
            case PRE:
                mRadioGroup.check(R.id.rb_pre);
                break;
            case PRODUCT:
                mRadioGroup.check(R.id.rb_product);
                break;
            default:
                mRadioGroup.check(R.id.rb_test);
                break;
        }
        //点击切换环境
        mRadioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.rb_test:
                    if (ConfigManager.getDefault().getAppEnv() != ConfigManager.EnvironmentType.TEST) {
                        ConfigManager.getDefault().saveAppEnv(ConfigManager.EnvironmentType.TEST);
                    }
                    break;
                case R.id.rb_pre:
                    if (ConfigManager.getDefault().getAppEnv() != ConfigManager.EnvironmentType.PRE) {
                        ConfigManager.getDefault().saveAppEnv(ConfigManager.EnvironmentType.PRE);
                    }
                    break;
                case R.id.rb_product:
                    if (ConfigManager.getDefault().getAppEnv() != ConfigManager.EnvironmentType.PRODUCT) {
                        ConfigManager.getDefault().saveAppEnv(ConfigManager.EnvironmentType.PRODUCT);
                    }
                    break;
            }
            Toast.makeText(this, "1s后关闭App,重启生效", Toast.LENGTH_SHORT).show();
            //退出app要进行退出登录和去除数据相关
            // system.exit(0)、finish、android.os.Process.killProcess(android.os.Process.myPid())区别:
            //可以杀死当前应用活动的进程,这一操作将会把所有该进程内的资源(包括线程全部清理掉)。
            //当然,由于ActivityManager时刻监听着进程,一旦发现进程被非正常Kill,它将会试图去重启这个进程。这就是为什么,有时候当我们试图这样去结束掉应用时,发现它又自动重新启动的原因。
            //1. System.exit(0) 表示是正常退出。
            //2. System.exit(1) 表示是非正常退出,通常这种退出方式应该放在catch块中。
            //3. Process.killProcess 或 System.exit(0)当前进程确实也被 kill 掉了,但 app 会重新启动。
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    Process.killProcess(Process.myPid());
                }
            }, 1000);
        });
    }
}










