PendingIntent的flag和原理解析

|-----------------------------------|---------------------------------------------------------------------------------------------------------------------------|
| flag | 含义 |
| PendingIntent.FLAG_CANCEL_CURRENT | 如果PendingIntent已经存在,则取消当前的PendingIntent,重新创建一个新的PendingIntent。 |
| PendingIntent.FLAG_NO_CREATE | 如果PendingIntent已经存在,则返回null,而不是重新创建一个新的PendingIntent。 |
| PendingIntent.FLAG_ONE_SHOT | 只能使用一次,使用后会自动取消。 |
| PendingIntent.FLAG_UPDATE_CURRENT | 如果PendingIntent已经存在,则更新当前的PendingIntent。 |
| PendingIntent.FLAG_IMMUTABLE | 表示创建的PendingIntent应该是不可变的??? |
| PendingIntent.FLAG_MUTABLE | 表示创建的PendingIntent应该是可变的??? |

PendingIntentController的getIntentSender方法中

java 复制代码
final boolean noCreate = (flags & PendingIntent.FLAG_NO_CREATE) != 0;
final boolean cancelCurrent = (flags & PendingIntent.FLAG_CANCEL_CURRENT) != 0;
final boolean updateCurrent = (flags & PendingIntent.FLAG_UPDATE_CURRENT) != 0;
flags &= ~(PendingIntent.FLAG_NO_CREATE | PendingIntent.FLAG_CANCEL_CURRENT
        | PendingIntent.FLAG_UPDATE_CURRENT);

PendingIntentRecord.Key key = new PendingIntentRecord.Key(type, packageName, featureId,
        token, resultWho, requestCode, intents, resolvedTypes, flags,
        new SafeActivityOptions(opts), userId);
WeakReference<PendingIntentRecord> ref;
ref = mIntentSenderRecords.get(key);
PendingIntentRecord rec = ref != null ? ref.get() : null;
if (rec != null) {
    if (!cancelCurrent) {
        if (updateCurrent) {
            // FLAG_UPDATE_CURRENT标签,则更新当前的pendingIntent
            if (rec.key.requestIntent != null) {
                rec.key.requestIntent.replaceExtras(intents != null ?
                        intents[intents.length - 1] : null);
            }
            if (intents != null) {
                intents[intents.length - 1] = rec.key.requestIntent;
                rec.key.allIntents = intents;
                rec.key.allResolvedTypes = resolvedTypes;
            } else {
                rec.key.allIntents = null;
                rec.key.allResolvedTypes = null;
            }
        }
        return rec;
    }
    // FLAG_CANCEL_CURRENT则先把当前的cancel掉,再重新创建一个pendingIntent
    makeIntentSenderCanceled(rec, CANCEL_REASON_SUPERSEDED);
    mIntentSenderRecords.remove(key);
    decrementUidStatLocked(rec);
}
if (noCreate) {
    // FLAG_NO_CREATE 则直接返回当前的pendingIntent
    return rec;
}
// 重新创建一个新的
rec = new PendingIntentRecord(this, key, callingUid);

在PendingIntentRecord的sendInner中

java 复制代码
if ((key.flags & PendingIntent.FLAG_ONE_SHOT) != 0) {
    // 如果是PendingIntent.FLAG_ONE_SHOT,则发送完就立刻cancel掉
    controller.cancelIntentSender(this, true, CANCEL_REASON_ONE_SHOT_SENT);
}