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.internal.nfc; 18 19import java.io.IOException; 20 21import android.nfc.IP2pInitiator; 22import android.os.RemoteException; 23import android.util.Log; 24 25/** 26 * P2pInitiator represents the initiator in an NFC-IP1 peer-to-peer 27 * communication. 28 * 29 * @see P2pTarget 30 */ 31public class P2pInitiator extends P2pDevice { 32 33 private static final String TAG = "P2pInitiator"; 34 35 /** 36 * The entry point for P2P tag operations. 37 */ 38 private final IP2pInitiator mService; 39 40 /** 41 * Internal constructor for the P2pInitiator class. 42 * 43 * @param handle The handle returned by the NFC service and used to identify 44 * the tag in subsequent calls. 45 */ 46 P2pInitiator(IP2pInitiator service, int handle) { 47 this.mService = service; 48 this.mHandle = handle; 49 } 50 51 /** 52 * Receives data from a P2pInitiator. 53 * 54 * @return data sent by the P2pInitiator. 55 * @throws IOException if the target has been lost or if the connection has 56 * been closed. 57 */ 58 public byte[] receive() throws IOException { 59 try { 60 byte[] result = mService.receive(mHandle); 61 if (result == null) { 62 throw new IOException("Tag has been lost"); 63 } 64 return result; 65 } catch (RemoteException e) { 66 Log.e(TAG, "RemoteException in receive(): ", e); 67 return null; 68 } 69 } 70 71 /** 72 * Sends data to a P2pInitiator. 73 * 74 * @param data data to be sent to the P2pInitiator. 75 * @throws IOException if the target has been lost or if the connection has 76 * been closed. 77 */ 78 public void send(byte[] data) throws IOException { 79 try { 80 boolean isSuccess = mService.send(mHandle, data); 81 if (!isSuccess) { 82 throw new IOException("Tag has been lost"); 83 } 84 } catch (RemoteException e) { 85 Log.e(TAG, "RemoteException in send(): ", e); 86 } 87 } 88 89 @Override 90 public byte[] getGeneralBytes() { 91 try { 92 return mService.getGeneralBytes(mHandle); 93 } catch (RemoteException e) { 94 Log.e(TAG, "RemoteException in getGeneralBytes(): ", e); 95 return null; 96 } 97 } 98 99 @Override 100 public int getMode() { 101 return P2pDevice.MODE_P2P_INITIATOR; 102 } 103 104} 105