在開發android app時,我們可能會有如下的需求:
正式版與測試版,會有正式版連線的API與測試版連線的API,
或是測試環境與正式環境有不同的ApplicatoinId時,
這時就可以使用Gradle productFlavors,依不同的版本設定不同的參數
在Gradle裡加上productFlavors ,將版本分為dev、prod
dev、prod各使用不同的applicationId
productFlavors {
dev {
applicationId
"evan.chen.app.productflavorsample.dev"
resValue
"string",
"version_type",
"Free Version" }
prod {
applicationId
"evan.chen.app.productflavorsample"
resValue
"string",
"version_type",
"Pro Version" }
}
接著建立一個Constants裡放API的網址。
public class Constants {
public static final String API_URL = "http://staging-api.evanchenapp.com";
}
public class Constants {
public static final String API_URL = "http://api.evanchenapp.com";
}
MainActivity 取得 API_URL
public class MainActivity
extends AppCompatActivity {
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.
activity_main);
Log.
d(
"Log",
"Url:" + Constants.
API_URL);
}
}
最後,在Build Variants選擇build的版本就可以了