在安卓开发中,动态的切换环境很重要,避免了很多的麻烦;
第一步:在app的gradle文件中进行配置
android { compileSdkVersion 28 defaultConfig { applicationId "com.example.demo" minSdkVersion 15 targetSdkVersion 28 versionCode 1 versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }
//下面为配置的内容
productFlavors { flavorDimensions "default" yp7000890 { dimension "default" manifestPlaceholders = [ CHANNEL_VALUE : "yp7000890",//标识 HOST_VALUE : "测试环境网址" ] } other { dimension "default" manifestPlaceholders = [ CHANNEL_VALUE : "other",//标识 HOST_VALUE : "正式环境网址" ] } } }
第二步:在清单文件中配置
<application android:name=".BaseApplication" android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> //以下为配置的内容 <meta-data android:name="com.example.demo.HOST" android:value="${HOST_VALUE}" /> <meta-data android:name="YOUPLUS_CHANNEL" android:value="${CHANNEL_VALUE}" />
<activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application>
第三步:传进BaseApplication继承Application
public class BaseApplication extends Application{ private static Context context; @Override public void onCreate() { super.onCreate(); context=getApplicationContext(); } public static Context getBaseApplicationContext(){ return context; } }
第四步:创建一个类ApiConstant
public class ApiConstant { public static String YP_HOST = ""; public static String YP_CHANNEL = ""; static { ApplicationInfo appInfo = null; try { appInfo = BaseApplication.getBaseApplicationContext().getPackageManager().getApplicationInfo(BaseApplication.getBaseApplicationContext().getPackageName(), PackageManager.GET_META_DATA); YP_HOST = appInfo.metaData.getString("com.example.demo.HOST"); YP_CHANNEL = appInfo.metaData.getString("YOUPLUS_CHANNEL"); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } }
第五步:在你需要的地方就可以找到你需要的网址了
public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); String BASE_URL =ApiConstant.YP_HOST; Log.e("TAG","BASE_URL:"+BASE_URL); } }