2 * Copyright (C) 2012 The CyanogenMod Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package com.android.settings.profiles;
19 import android.content.Context;
20 import android.nfc.NdefMessage;
21 import android.nfc.NdefRecord;
22 import android.nfc.Tag;
23 import android.nfc.tech.Ndef;
24 import android.nfc.tech.NdefFormatable;
25 import android.os.Vibrator;
26 import android.util.Log;
28 import cyanogenmod.app.Profile;
30 import java.io.IOException;
31 import java.util.UUID;
33 public class NFCProfileUtils {
35 private static final String TAG = "NFCUtils";
37 private static final long[] VIBRATION_PATTERN = {
41 public static void vibrate(Context context) {
42 Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
43 vibrator.vibrate(VIBRATION_PATTERN, -1);
47 * Writes an NdefMessage to a NFC tag
49 public static boolean writeTag(NdefMessage message, Tag tag) {
50 int size = message.toByteArray().length;
52 Ndef ndef = Ndef.get(tag);
55 if (!ndef.isWritable()) {
56 Log.e(TAG, "Tag is not writable!");
59 if (ndef.getMaxSize() < size) {
61 "Tag exceeds max ndef message size! [" + size + " > "
62 + ndef.getMaxSize() + "]");
65 ndef.writeNdefMessage(message);
68 NdefFormatable format = NdefFormatable.get(tag);
72 format.format(message);
74 } catch (IOException e) {
75 Log.e(TAG, "Write error!", e);
82 } catch (Exception e) {
83 Log.e(TAG, "Write error!", e);
88 /* Convert a 16-byte array to a UUID */
89 static UUID toUUID(byte[] byteArray) {
93 for (int i = 0; i < 8; i++) {
94 msb = (msb << 8) | (byteArray[i] & 0xff);
96 for (int i = 8; i < 16; i++) {
97 lsb = (lsb << 8) | (byteArray[i] & 0xff);
99 UUID result = new UUID(msb, lsb);
104 /* Convert a UUID to a 16-byte array */
105 static byte[] asByteArray(UUID uuid) {
106 long msb = uuid.getMostSignificantBits();
107 long lsb = uuid.getLeastSignificantBits();
108 byte[] buffer = new byte[16];
110 for (int i = 0; i < 8; i++) {
111 buffer[i] = (byte) (msb >>> 8 * (7 - i));
113 for (int i = 8; i < 16; i++) {
114 buffer[i] = (byte) (lsb >>> 8 * (7 - i));
121 * Convert a profiles into an NdefMessage. The profile UUID is 16 bytes and
122 * stored with the cm/profile mimetype
124 public static NdefMessage getProfileAsNdef(Profile profile) {
125 byte[] profileBytes = NFCProfileUtils.asByteArray(profile.getUuid());
127 NdefRecord record = NdefRecord.createMime(NFCProfile.PROFILE_MIME_TYPE, profileBytes);
128 return new NdefMessage(new NdefRecord[] { record });