1 /* 2 * Copyright (C) 2011 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 17 package com.android.nfc.ndefpush; 18 19 import com.android.nfc.DeviceHost.LlcpSocket; 20 import com.android.nfc.LlcpException; 21 import com.android.nfc.NfcService; 22 23 import android.nfc.NdefMessage; 24 import android.util.Log; 25 26 import java.io.IOException; 27 import java.util.Arrays; 28 29 /** 30 * Simple client to push the local NDEF message to a server on the remote side of an 31 * LLCP connection, using the Android Ndef Push Protocol. 32 */ 33 public class NdefPushClient { 34 private static final String TAG = "NdefPushClient"; 35 private static final int MIU = 128; 36 private static final boolean DBG = true; 37 push(NdefMessage msg)38 public boolean push(NdefMessage msg) { 39 NfcService service = NfcService.getInstance(); 40 41 // We only handle a single immediate action for now 42 NdefPushProtocol proto = new NdefPushProtocol(msg, NdefPushProtocol.ACTION_IMMEDIATE); 43 byte[] buffer = proto.toByteArray(); 44 int offset = 0; 45 int remoteMiu; 46 LlcpSocket sock = null; 47 try { 48 if (DBG) Log.d(TAG, "about to create socket"); 49 // Connect to the my tag server on the remote side 50 sock = service.createLlcpSocket(0, MIU, 1, 1024); 51 if (sock == null) { 52 throw new IOException("Could not connect to socket."); 53 } 54 if (DBG) Log.d(TAG, "about to connect to service " + NdefPushServer.SERVICE_NAME); 55 sock.connectToService(NdefPushServer.SERVICE_NAME); 56 57 remoteMiu = sock.getRemoteMiu(); 58 if (DBG) Log.d(TAG, "about to send a " + buffer.length + " byte message"); 59 while (offset < buffer.length) { 60 int length = Math.min(buffer.length - offset, remoteMiu); 61 byte[] tmpBuffer = Arrays.copyOfRange(buffer, offset, offset+length); 62 if (DBG) Log.d(TAG, "about to send a " + length + " byte packet"); 63 sock.send(tmpBuffer); 64 offset += length; 65 } 66 return true; 67 } catch (IOException e) { 68 Log.e(TAG, "couldn't send tag"); 69 if (DBG) Log.d(TAG, "exception:", e); 70 } catch (LlcpException e) { 71 // Most likely the other side doesn't support the my tag protocol 72 Log.e(TAG, "couldn't send tag"); 73 if (DBG) Log.d(TAG, "exception:", e); 74 } finally { 75 if (sock != null) { 76 try { 77 if (DBG) Log.d(TAG, "about to close"); 78 sock.close(); 79 } catch (IOException e) { 80 // Ignore 81 } 82 } 83 } 84 return false; 85 } 86 } 87