简体   繁体   English

课堂上的良好实践摇篮风味

[英]Good Practice Gradle Flavors With Class

I am looking for informations about how I should use gradle flavors to define my behaviors for an Android Application. 我正在寻找有关如何使用gradle样式定义Android应用程序行为的信息。

Let's say I want to start a new activity in my flavor1 and not in my flavor2. 假设我要在我的flavor1中而不是在flavor2中开始新的活动。

As gradle doesn't override classes with each other, 由于gradle不会相互覆盖类,

I have to, define the Activity in each flavors 我必须定义每种口味的活动

app/src/
     |-> flavor1/java/<package>/Activity.java
     |-> flavor2/java/<package>/Activity.java
     |-> main/java/<package>

or, define it in my main folder and use an enum in a Constant class which return if I am in my flavor1 or my flavor2 或者,在我的主文件夹中定义它,并在Constant类中使用一个枚举,如果我属于我的flavor1或我的flavor2,则返回该枚举

app/src/
     |-> flavor1/java/<package>/Constant.java
     |-> flavor2/java/<package>/Constant.java
     |-> main/java/<package>/Activity.java

My guess is that I have to mix both solutions: 我的猜测是我必须混合使用两种解决方案:

  • If I want to create a unique activity in flavor1, I have to create this same class in flavor2 and maybe just throw RuntimeException("stub!") 如果要在flavor1中创建唯一的活动,则必须在flavor2中创建相同的类,并且可能只是throw RuntimeException("stub!")
  • If I want to call this activity from main , I have to use something like if (Constant.getFlavor() == flavor1) 如果要从main调用此活动,则必须使用诸如if (Constant.getFlavor() == flavor1)

In my opinion, this is the coolest way to use gradle flavors. 我认为,这是使用gradle口味的最酷方法。 But I want to be sure that there is no other best ways, so far discovered, to deal with it before the final implementation. 但是我想确定,到目前为止,没有其他最佳方法可以在最终实现之前对其进行处理。

Is there anyone who blogged something about it or want to give his own opinion ? 有没有人在博客上写过一些东西或想发表自己的看法? I would love to read you! 我很想读你!

Thanks in advance! 提前致谢!

You can place different AndroidManifest files on each flavor. 您可以在每种口味上放置不同的AndroidManifest文件。 For example you can define the (let's call it) optional Activity inside the flavor1, the Class that extends the optional Activity just inside the flavor1 and you're done! 例如,您可以在flavor1内定义(让我们称呼它)可选的Activity,在flavor1内扩展可选的Activity的Class,您就完成了! Please note that the flavor AndroidManifest file must specify only what is different from the main AndroidManifest: in this case, you should include just the <activity/> (of course inside an empty <application/> ) 请注意,风味AndroidManifest文件必须仅指定与主要AndroidManifest的区别:在这种情况下,您应该仅包含<activity/> (当然在空的<application/>

If you wanted to avoid the if (Constant.getFlavor() == flavor1) you could create a factory class which then returns the correct intent for that flavours Activity. 如果要避免if (Constant.getFlavor() == flavor1) ,则可以创建一个工厂类,该工厂类然后为该Activity返回正确的意图。 Then override this in each flavour. 然后在每种口味中将其覆盖。 This avoids polluting the code with if statements. 这样可以避免使用if语句污染代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM