NdefMessageParser.java revision 081de56bfdd18f47025ef7af85b45592db244233
1/* 2 * Copyright (C) 2010 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.apps.tag.message; 18 19import android.nfc.NdefMessage; 20import android.nfc.NdefRecord; 21 22import com.android.apps.tag.record.ImageRecord; 23import com.android.apps.tag.record.MimeRecord; 24import com.android.apps.tag.record.ParsedNdefRecord; 25import com.android.apps.tag.record.SmartPoster; 26import com.android.apps.tag.record.TextRecord; 27import com.android.apps.tag.record.UriRecord; 28 29import java.util.ArrayList; 30import java.util.List; 31 32/** 33 * Utility class for creating {@link ParsedNdefMessage}s. 34 */ 35public class NdefMessageParser { 36 37 // Utility class 38 private NdefMessageParser() { } 39 40 /** Parse an NdefMessage */ 41 public static ParsedNdefMessage parse(NdefMessage message) { 42 List<ParsedNdefRecord> elements = getRecords(message); 43 44 if (elements.isEmpty()) { 45 return new EmptyMessage(); 46 } 47 48 ParsedNdefRecord first = elements.get(0); 49 50 if (elements.size() == 1) { 51 if (first instanceof SmartPoster) { 52 return new SmartPosterMessage((SmartPoster) first, elements); 53 } 54 if (first instanceof TextRecord) { 55 return new TextMessage((TextRecord) first, elements); 56 } 57 if (first instanceof UriRecord) { 58 return new UriMessage((UriRecord) first, elements); 59 } 60 } 61 62 return new UnknownMessage(elements); 63 } 64 65 public static List<ParsedNdefRecord> getRecords(NdefMessage message) { 66 List<ParsedNdefRecord> elements = new ArrayList<ParsedNdefRecord>(); 67 for (NdefRecord record : message.getRecords()) { 68 if (UriRecord.isUri(record)) { 69 elements.add(UriRecord.parse(record)); 70 } else if (TextRecord.isText(record)) { 71 elements.add(TextRecord.parse(record)); 72 } else if (SmartPoster.isPoster(record)) { 73 elements.add(SmartPoster.parse(record)); 74 } else if (ImageRecord.isImage(record)) { 75 elements.add(ImageRecord.parse(record)); 76 } else if (MimeRecord.isMime(record)) { 77 elements.add(MimeRecord.parse(record)); 78 } 79 } 80 return elements; 81 } 82} 83