在安卓开发中,动态获取域名常用于以下场景:
原理:将域名存储在本地配置文件(如JSON/XML),运行时读取。
// assets/config.json { "domain": "https://api.example.com" } // 读取代码 public String getDomainFromAssets(Context context) { try { InputStream is = context.getAssets().open("config.json"); byte[] buffer = new byte[is.available()]; is.read(buffer); String json = new String(buffer, "UTF-8"); JSONObject obj = new JSONObject(json); return obj.getString("domain"); } catch (Exception e) { e.printStackTrace(); return "https://default.com"; // 默认值 } }
优点:简单易实现,无需网络请求
缺点:需重新打包更新配置,不适合高频变动场景
原理:通过远程接口获取最新域名配置。
// Retrofit接口定义 @GET("config/domain") Call<DomainConfig> getDomainConfig(); // 使用示例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://config-server.com/") .build(); ApiService service = retrofit.create(ApiService.class); service.getDomainConfig().enqueue(new Callback<DomainConfig>() { @Override public void onResponse(Call<DomainConfig> call, Response<DomainConfig> response) { String domain = response.body().getDomain(); // 更新网络请求的baseUrl } @Override public void onFailure(Call<DomainConfig> call, Throwable t) { // 错误处理 } });
优点:配置可实时更新
缺点:依赖网络,首次启动可能延迟
原理:利用Firebase配置服务管理域名参数。
// 初始化Remote Config FirebaseRemoteConfig mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance(); FirebaseRemoteConfigSettings configSettings = new FirebaseRemoteConfigSettings.Builder() .setDeveloperModeEnabled(BuildConfig.DEBUG) .build(); mFirebaseRemoteConfig.setConfigSettings(configSettings); // 获取域名 String domain = mFirebaseRemoteConfig.getString("app_domain");
优点:可视化控制台管理,支持AB测试
缺点:需集成Firebase SDK,国内网络可能受限
原理:将域名配置写入HTML文件,通过WebView解析。
<!-assets/config.html --> <html> <body> <script> window.domain = "https://dynamic.example.com"; </script> </body> </html>
// 读取代码 WebView webView = new WebView(context); webView.loadUrl("file:///android_asset/config.html"); webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { String domain = view.evaluateJavascript("window.domain") + ""; // 使用domain进行网络请求 } });
优点:可嵌入复杂逻辑(如加密配置)
缺点:性能开销较大,存在跨域安全问题
方案 | 实时性 | 实现难度 | 维护成本 | 适用场景 |
---|---|---|---|---|
本地配置文件 | 低 | 固定环境切换 | ||
网络请求 | 高 | 高频变动场景 | ||
Firebase配置 | 中 | 多版本控制 | ||
WebView | 中 | 特殊安全需求 |
A1:
使用本地存储(如SP或MMKV)缓存域名,设置过期时间。
// 读取缓存 String cachedDomain = SPUtils.getString("domain", null); if (cachedDomain != null && !isExpired()) { return cachedDomain; } // 发起网络请求获取新域名...
A2:
若域名不固定,需配置Network Security Config
:
res/xml/network_security_config.xml
添加: <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">.example.com</domain> </domain-config>
AndroidManifest.xml
引用: <application ...> <network-security-config android:resource="@xml/network_security_config" /> </application>
此配置允许所有example.com
子域名的明文通信,实际使用中建议配合证书