Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

java - Intent.addFlags using for loop

Does adding flags to an intent using a for loop, overwrite the previous flag added in the loop?

Example 1:

What I want to achieve

int[] flags = {Intent.FLAG_ACTIVITY_NEW_TASK, Intent.FLAG_ACTIVITY_CLEAR_TASK};

for (int flag: flags) {
     intent.addFlags(flag);
}

Example 2:

How flags are normally added

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

Example 3:

Simple code representation of the for loop in Example 1

intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);

REASON:

Example 4:

I am passing flags into a method

public void startActivity(int[] flags) {
      for (int flag: flags) {
          intent.addFlags(flag);
      }
}

Resolution:

If a for loop does overwrite the previously added flag, how can I achieve the code seen in Example 2 using the method seen in Example 4?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not actually familiar with android Intent, but it seems you're simply combining bits stored in integers, so you could do something like this:

int combinedFlags = 0;
for (int flag : flags) {
    combinedFlags |= flag;
}
intent.addFlags(combinedFlags);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...