110

What is difference between setFlags and addFlags for intent. Could any one explain it please. Help Appreciated.

user755499
  • 2,241
  • 4
  • 25
  • 34
  • 1
    I always appreciate a link to the official docs: https://developer.android.com/reference/android/view/Window.html#addFlags(int) and/or https://developer.android.com/reference/android/view/Window.html#setFlags(int,%20int) – MarkHu Jan 30 '19 at 19:48

3 Answers3

144

When you use setFlags you are replacing the old flags... when you use addFlags you are appending new flags. Remember, a flag is just a integer which is power of two... in binary, flags look like this: 1, 10, 100, 1000, etc... (which in this case are 1, 2, 4, 8). So, what addFlags does is appending the integer you pass using the | operator.

// example... 
// value of flags: 1
intent.setFlags(2|4); 
// now flags have this value: 110
intent.addFlags(8); 
// now flags have this value: 1110
Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
Cristian
  • 198,401
  • 62
  • 356
  • 264
  • How can it possible `intent.setFlags(2|4);` will give 110 value – Gopal Singh Sirvi Apr 11 '15 at 09:12
  • 6
    @GopalSinghSirvi in binary the LSB (least significant bit) for human readable values is the most right one. that means that the 0 of the 110 represents the value 2^0 = 1 . The second value 1 represents 2^1 = 2. And the third value represents 2^2=4. So using the OR | operator on 4 (100) and 2(010) is 110 – Patric Oct 28 '15 at 19:31
  • This should not be confused with Window.setFlags/addFlags which have a different behaviour to the Intent methods. – TheIT Nov 22 '15 at 20:55
  • May I know the uses of these intent flags? or can you tag me to the appropriate question? – Anish Kumar Feb 26 '18 at 12:09
  • What are the flags that are set to an Intent by default? i.e. what exactly does gets reset when we use Intent().setFlags()? – M.Ed Nov 08 '22 at 07:43
10
intent.setFlags(int num);

This set flag controls how to handle the Intent.setflag mainly depends on type of component being executed by the Intent.It returns the same intent object for chaining multiple calls into a single statement.

intent.addFlags(int num);

This helps to add additional flags to a particular intent with the existing values.this also returns the same intent object for chaining multiple calls into a single statement.

Sreedev
  • 6,563
  • 5
  • 43
  • 66
8
 public Intent addFlags(int flags) {
    mFlags |= flags;
    return this;
}
public Intent setFlags(int flags) {
    mFlags = flags;
    return this;
}

Just found this from the source code,for reference.

Haldir65
  • 81
  • 1
  • 1