传输文件的API
从Android4.1开始,NfcAdapter类增加了如下两个推送数据的方法。
NfcAdapter.setBeamPushUris
NfcAdapter.setBeamPushUrisCallback
这两个方法的原型如下:
public void setBeamPushUris(Uri[] uris, Activity activity);
public void setBeamPushUrisCallback(CreateBeamUrisCallback callback, Activity activity);
Demo
1 import java.io.FileOutputStream; 2 import java.io.InputStream; 3 4 import android.app.Activity; 5 import android.app.PendingIntent; 6 import android.content.Intent; 7 import android.net.Uri; 8 import android.nfc.NfcAdapter; 9 import android.nfc.NfcAdapter.CreateBeamUrisCallback; 10 import android.nfc.NfcEvent; 11 import android.os.Bundle; 12 13 14 public class NFCFileActivity extends Activity implements CreateBeamUrisCallback { 15 private NfcAdapter mNfcAdapter; 16 private PendingIntent mPendingIntent; 17 private final String targetFilename = "/sdcard/temp_icon.png"; 18 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_nfcfile); 23 24 mNfcAdapter = mNfcAdapter.getDefaultAdapter(this); 25 mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 26 getClass()), 0); 27 28 try { 29 InputStream is = getResources().getAssets().open("icon.png"); 30 FileOutputStream fos = new FileOutputStream(targetFilename); 31 byte[] buffer = new byte[10000]; 32 int n = is.read(buffer); 33 fos.write(buffer, 0, n); 34 fos.close(); 35 is.close(); 36 } catch (Exception e) { 37 38 } 39 mNfcAdapter.setBeamPushUrisCallback(this, this); 40 } 41 42 @Override 43 public Uri[] createBeamUris(NfcEvent event) { 44 Uri[] uris = new Uri[1]; 45 Uri uri = Uri.parse("file://" + targetFilename); 46 uris[0] = uri; 47 return uris; 48 } 49 50 }
1 <uses-permission android:name="android.permission.NFC" /> 2 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
其实内部是蓝牙在传输,NFC已经不起作用了,可以相隔一定距离,即使NFC中断也没关系,因为是蓝牙在传输。