我尝试使用 Google Search 和 Stack Overflow 进行搜索,但没有显示任何结果。我在开源库代码中看到过这个:
Notification notification = new Notification(icon, tickerText, when);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
"|=" ( pipe equal operator
) 是什么意思?
|=
读取方式与 相同+=
。是相同的
其中
|
是按位 OR 运算符。此处引用了所有运算符。
使用按位运算符是因为经常使用这些常量使 int 能够携带标志。
如果您查看这些常量,您会发现它们是 2 的幂:
public static final int DEFAULT_SOUND = 1; public static final int DEFAULT_VIBRATE = 2; // is the same than 1<<1 or 10 in binary public static final int DEFAULT_LIGHTS = 4; // is the same than 1<<2 or 100 in binary
所以你可以使用按位或来添加标志
int myFlags = DEFAULT_SOUND | DEFAULT_VIBRATE; // same as 001 | 010, producing 011
所以
只是意味着我们添加了一个标志。
并且对称地,我们使用
&
以下方法测试标志是否设置:boolean hasVibrate = (DEFAULT_VIBRATE & myFlags) != 0;