[英]How to compare two Intents for equality
現在,我在IntentService
中有一個Intents的LinkedList
,它可以跟蹤Service
排隊的Intent。 我發現,即使對於相同的Intent, contains()
方法也永遠不會返回true。 比較兩個Intent,我還有別的事情要做嗎?
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(queue.contains(intent)){
//Never reaches here
intent.setAction(NO_ACTION);
}
queue.push(intent);
return super.onStartCommand(intent, flags, startId);
}
發送意圖的示例代碼:
Intent i = new Intent(context, NodeIndexService.class);
i.setAction(NodeIndexService.REFRESH);
i.putExtra(NodeIndexService.TYPE, indexType);
i.putExtra(NodeIndexService.RESULT_RECEIVER, receiver);
context.startService(i);
與此代碼一個接一個發送的兩個Intent應該相同,不是嗎? 上下文沒有改變,其他功能也相同。
有一種專門比較意圖的方法-filterEquals(): http : //developer.android.com/reference/android/content/Intent.html#filterEquals (android.content.Intent)
使用此方法時,具有相同數據,類別和動作的意圖看起來將被視為相等。
您需要定義自己的equals
方法以滿足您的相等性標准,無論它們是什么。
根據Intent
API文檔 , equals
方法由Object
標識定義。
這或多或少是標准的Java基礎。 看看這個類定義了自己的平等,如果沒有,您需要創建自己的-與任何環境的情況下,在還可以檢查平等的警告,所以是值得推行equals
和hashCode
正確 。
(如果您定義一個equals
,則需要定義一個hashCode
以確保完整性。)
您的代碼專門創建了新的意圖,這就是new
意圖。
您正在創建兩個對象:對象標識意味着查看兩個引用是否指向完全相同的對象 ,而不是任意屬性是否相同。 如果要基於任意條件進行比較,則需要定義自己的equals
方法來執行您關心的比較。
您可以使用Intent.toUri(0)
將意圖轉換為URI並比較結果字符串。 如果它們具有相同的動作,類別,類型,標志,包,組件和其他內容,則它們將是相等的。
你能做這樣的事情嗎?
Object ob1 = (Object) intent1;
Object ob2 = (Object) intent2;
if(ob1.equals(ob2))
只有當關於它們的一切都相同時,以上內容才會成立
您要比較意圖的任何特定部分嗎?
if(intent1.getAction().equals(intent2.getAction()) && intent1.getType().equals(intent2.getType()) &&
intent1.getExtras().equals(intent2.getExtras()))
在這里,我使用比較器比較兩個意圖(在使用FEST的單元測試中):
import static org.fest.assertions.api.Assertions.assertThat;
assertThat(intentOne).usingComparator(new IntentComparator()).isEqualTo(intentTwo);
private static class IntentComparator implements Comparator<Intent> {
@Override
public int compare(Intent left, Intent right) {
return left.filterEquals(right) ? 0 : 1;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.