gradle 与 buildConfigField

定义buildConfigField

格式 : buildConfigField(String type,String name,String value);


android {
    buildTypes {
        release {
            // 不显示Log
            buildConfigField "boolean", "LOG_DEBUG", "false"
             //动态赋值url和端口
            buildConfigField('String', 'BASE_URL', '"https://www.baidu.com/"')
            buildConfigField('int', 'URL_PORT', '5672')
        }
        debug {
            // 显示Log
            buildConfigField "boolean", "LOG_DEBUG", "true"
            //动态赋值url和端口
            buildConfigField('String', 'BASE_URL', '"https://www.sogou.com/"')
            buildConfigField('int', 'URL_PORT', '8888')
        }
    }
}

sync一下之后,CTRL+N 打开 搜索: BuildConfig:

public final class BuildConfig {
  public static final boolean DEBUG = Boolean.parseBoolean("true");
  public static final String APPLICATION_ID = "com.xq.mygradle2.debug";
  public static final String BUILD_TYPE = "debug";
  public static final String FLAVOR = "";
  public static final int VERSION_CODE = 1;
  public static final String VERSION_NAME = "1.0";
  // Fields from build type: debug
  public static final String BASE_URL = "https://www.sogou.com/";
  public static final boolean LOG_DEBUG = true;
  public static final int URL_PORT = 8888;
}

可看到生成的字段和值。

引用:

public class MainActivity extends AppCompatActivity {

    private static final String TAG = MainActivity.class.getSimpleName();
    public static final String URL = BuildConfig.BASE_URL + ":" + BuildConfig.URL_PORT;

    private TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.tv = (TextView) findViewById(R.id.tv);
        tv.setText(URL);
    }
}

运行查看效果

点击gradle按钮:

installDebug
installRelease

安装后可看到不同的效果。

你可能感兴趣的:(gradle)