How to combine Intent flags in Kotlin
Asked Answered
W

3

73

I want to combine two intent flags as we do below in Android:

Intent intent = new Intent(this, MapsActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);

I tried doing something like this but it didn't work for me:

val intent = Intent(context, MapActivity::class.java)
intent.flags = (Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK)
Wonky answered 1/9, 2017 at 7:41 Comment(0)
T
123

Explanation:

The operation that is applied to the flags is a bitwise or. In Java you have the | operator for that.

As of bitwise operations [in Kotlin], there're no special characters for them, but just named functions that can be called in infix form.

Source

Here a list of all bitwise operations for Int and Long

  • shl(bits) – signed shift left (Java's <<)
  • shr(bits) – signed shift right (Java's >>)
  • ushr(bits) – unsigned shift right (Java's >>>)
  • and(bits) – bitwise and (Java's &)
  • or(bits) – bitwise or (Java's |)
  • xor(bits) – bitwise xor (Java's ^)
  • inv() – bitwise inversion (Java's ~)

Solution:

So, in your case you only need to call or in between your arguments like so.

intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
Tum answered 1/9, 2017 at 8:20 Comment(2)
Does or execute only one of them? Can I use and?Celebrant
I know how bitwise or works but with the naming of the bitwise or operator as 'or', at first glance 'FlagA or FlagB' does not convey that in fact this is a combination of FlagA and FlagB.Tipper
K
17

Try something like following:

val intent = Intent(this, MapsActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK
Kicksorter answered 1/9, 2017 at 8:5 Comment(0)
M
5

Advanced, Reuseable Kotlin:

In Kotlin or is the replacement for the Java bitwise or |.

intent.flags = FLAG_ACTIVITY_NEW_TASK or FLAG_ACTIVITY_CLEAR_TASK

If you plan to use your combination regularly, create an Intent extension function

fun Intent.clearStack() {
    flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}

You can then directly call this function before starting the intent

intent.clearStack()

If you need the option to add additional flags in other situations, add an optional param to the extension function.

fun Intent.clearStack(additionalFlags: Int = 0) {
    flags = additionalFlags or Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
}
Monde answered 9/1, 2020 at 18:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.