Android使用NFC分享文件

本文介绍了Android Beam如何利用NFC技术在设备间传输文件,详细讲解了发送和接收文件的步骤,包括权限设置、API使用、回调函数创建以及如何处理接收的文件。此外,还强调了在不同系统版本和文件类型的处理策略。
部署运行你感兴趣的模型镜像

1.NFC的定义


  NFC:近距离无线通讯技术

  Android Beam:是一个基于近场通信所做的新功能,这个功能可以为其他手机分享你正在使用的功能。

  Android允许你通过Android Beam文件传输功能在设备之间传送大文件。这个功能键具有简单的API,同时,它允许用户仅需要点击设备就能启动文件传输的过程。Android Beam会自动地将文件从一台设备拷贝至另外一台,并且在完成时告知用户。
  Android Beam文件传输API可以用来处理大量的数据,而在Android4.0(API Level 14)引入的Android BeamNDEF传输API则用来处理少量的数据,比如:URI等一些体积较小的数据。另外,Android Beam是在Android NFC框架中唯一允许你从NFC标签中读取NDEF消息的方法。


2.发送文件给其他设备


  发送文件,首先需要声明使用NFC和外部存储的权限,你需要测试一下你的设备是否支持NFC,这样,你才能够向Android Beam文件传输提供文件的URI。

  使用Android Beam文件传输功能有下列要求:
  1>Android Beam文件传输功能只能在Android 4.1(API Level 16)及以上使用。
  2>你希望传送的文件必须放置于外部存储
  3>每个你希望传送的文件必须是全局可读的。你可以通过File.setReadable(true,false)来为文件设置相应的读权限
  4>你必须提供你要传输文件的URI。Android Beam文件传输无法处理由FileProvider.getUriForFile()生成的URI。


声明权限

  NFC:允许你的应用通过NFC发送数据

<uses-permission android:name="android.permission.NFC" />

  READ_EXTERNAL_STORAGE:允许你的应用读取外部存储

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  注意:对于Android 4.2.2(API Level 17)及之前的系统版本,这个权限不是必需的。在后续的系统版本中,若应用需要读取外部存储,可能会需要申明该权限。为了保证将来程序稳定性,建议在该权限申明变成必需的之前,就在清单文件中声明好。

指定NFC功能

  指定你的应用使用NFC,添加<uses-feature>标签作为一个<manifest>标签的子标签。设置android:required属性字段为true,这样可以使得你的应用只有在NFC可以使用时,才能运行。

<uses-feature
    android:name="android.hardware.nfc"
    android:required="true" />

  注意,如果你的应用将NFC作为可选的一个功能,但期望在NFC不可使用时程序还能继续执行,你就应该设置android:required属性字段为false,然后在代码中测试NFC的可用性。


指定Android Beam文件传输

  由于Android Beam文件传输只能在Android 4.1(API Level 16)及以上的平台使用,如果你的应用将Android Beam文件传输作为一个不可缺少的核心模块,那么你必须指定<uses-sdk>标签为:android:minSdkVersion="16"。或者,你可以将android:minSdkVersion设置为其它值,然后在代码中测试平台版本。


测试设备是否支持Android Beam文件传输

  定义NFC是可选的,你应该使用下面的标签:

<uses-feature android:name="android.hardware.nfc" android:required="false" />

  如果你设置了android:required="false",你必须要在代码中测试NFC和Android Beam文件传输是否被支持。
  为了在代码中测试Android Beam文件传输,我们先通过PackageManager.hasSystemFeature()和参数FEATURE_NFC,来测试设备是否支持NFC。下一步,通过SDK_INT的值测试系统版本是否支持Android Beam文件传输。如果Android Beam文件传输是支持的,那么获得一个NFC控制器的实例,它能允许你与NFC硬件进行通信。

public class MainActivity extends Activity {
    ...
    NfcAdapter mNfcAdapter;
    // Flag to indicate that Android Beam is available
    boolean mAndroidBeamAvailable  = false;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // NFC isn't available on the device
        if (!PackageManager.hasSystemFeature(PackageManager.FEATURE_NFC)) {
            /*
             * Disable NFC features here.
             * For example, disable menu items or buttons that activate
             * NFC-related features
             */
            ...
        // Android Beam file transfer isn't supported
        } else if (Build.VERSION.SDK_INT <
                Build.VERSION_CODES.JELLY_BEAN_MR1) {
            // If Android Beam isn't available, don't continue.
            mAndroidBeamAvailable = false;
            /*
             * Disable Android Beam file transfer features here.
             */
            ...
        // Android Beam file transfer is available, continue
        } else {
            mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
            ...
        }
    }
    ...
}


创建一个提供文件的回调函数

  一旦你确认了设备支持Android Beam文件传输,那么可以添加一个回调函数,当Android Beam文件传输监测到用户希望与另一个支持NFC的设备发送文件时,系统会调用它。在该回调函数中,返回一个Uri对象数组,Android Beam文件传输将URI对应的文件拷贝发送给要接收的设备。
  要添加这个回调函数,我们需要实现NfcAdapter.CreateBeamUrisCallback接口,和它的方法:createBeamUris()

public class MainActivity extends Activity {
    ...
    // List of URIs to provide to Android Beam
    private Uri[] mFileUris = new Uri[10];
    ...
    /**
     * Callback that Android Beam file transfer calls to get
     * files to share
     */
    private class FileUriCallback implements
            NfcAdapter.CreateBeamUrisCallback {
        public FileUriCallback() {
        }
        /**
         * Create content URIs as needed to share with another device
         */
        @Override
        public Uri[] createBeamUris(NfcEvent event) {
            return mFileUris;
        }
    }
    ...
}
一旦你实现了这个接口,通过调用setBeamPushUrisCallback())将回调函数提供给Android Beam文件传输。

public class MainActivity extends Activity {
    ...
    // Instance that returns available files from this app
    private FileUriCallback mFileUriCallback;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        // Android Beam file transfer is available, continue
        ...
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        /*
         * Instantiate a new FileUriCallback to handle requests for
         * URIs
         */
        mFileUriCallback = new FileUriCallback();
        // Set the dynamic callback for URI requests.
        mNfcAdapter.setBeamPushUrisCallback(mFileUriCallback,this);
        ...
    }
    ...
}

  Note:你也可以将Uri对象数组通过你应用的NfcAdapter实例,直接提供给NFC框架。如果你能在NFC触碰事件发生之前,定义这些URI,那么你可以选择这个方法。


定义要发送的文件

  为了将一个或更多个文件发送给支持NFC的设备,需要为每一个文件获取一个文件URI(一个具有文件格式(file scheme)的URI),然后将它们添加至一个Uri对象数组中。要传输一个文件,你必须也有读文件的权限。

/*
     * Create a list of URIs, get a File,
     * and set its permissions
     */
    private Uri[] mFileUris = new Uri[10];
    String transferFile = "transferimage.jpg";
    File extDir = getExternalFilesDir(null);
    File requestFile = new File(extDir, transferFile);
    requestFile.setReadable(true, false);
    // Get a URI for the File and add it to the list of URIs
    fileUri = Uri.fromFile(requestFile);
    if (fileUri != null) {
        mFileUris[0] = fileUri;
    } else {
        Log.e("My Activity", "No File URI available for file.");
    }

3.接受其他设备的文件


  Android Beam文件传输将文件拷贝至接收设备上的一个特殊目录。同时使用Android Media Scanner扫描拷贝的文件,并在MediaStore provider中为媒体文件添加对应的条目记录。


响应请求并显示数据

  当Android Beam文件传输将文件拷贝至接收设备后,它会发布一个通知包含了一个Intent,它有一个ACTION_VIEW的Action,第一个传输文件的MIME类型,和一个指向第一个文件的URI。当用户点击了这个通知后,intent会被发送至系统。为了让你的应用能够响应这个intent,我们需要为响应的Activity所对应的<activity>标签添加<intent-filter>标签,在<intent-filter>标签中,添加下面的子标签: 

<action android:name="android.intent.action.VIEW" />

  用来匹配通知中的intent。

<category android:name="android.intent.category.CATEGORY_DEFAULT" />

  匹配隐式的Intent。

<data android:mimeType="mime-type" />

  匹配一个MIME类型。要指定那些你的应用能够处理的类型。


  下面的例子展示了如何添加一个intent filter来激活你的activity:

    <activity
        android:name="com.example.android.nfctransfer.ViewActivity"
        android:label="Android Beam Viewer" >
        ...
        <intent-filter>
            <action android:name="android.intent.action.VIEW"/>
            <category android:name="android.intent.category.DEFAULT"/>
            ...
        </intent-filter>
    </activity>

  注意:不仅仅只有Android Beam文件传输会发送含有ACTION_VIEW的intent。在接收设备上的其它应用也有可能会发送含有该行为的intent。


请求文件读权限

  如果要读取Android Beam文件传输所拷贝到设备上的文件,需要READ_EXTERNAL_STORAGE权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

  如果你希望将文件拷贝至你自己应用的存储区,那么需要的权限改为WRITE_EXTERNAL_STORAGE,另外WRITE_EXTERNAL_STORAGE权限包含了READ_EXTERNAL_STORAGE权限。

获取拷贝文件的目录

  Android Beam文件传输一次性将所有文件拷贝到目标设备的一个目录内,Android Beam文件传输通知所发出的Intent中包含有URI,他指向了第一个传输的文件。然而,你的应用也有可能接收到除了Android Beam文件传输之外的某个来源所发出的含有ACTION_VIEW行为的Intent。为了明确你应该如何处理接收的Intent,你需要检查它的scheme和authority。

  为了获得URI的scheme,调用Uri.getScheme()。

public class MainActivity extends Activity {
    ...
    // A File object containing the path to the transferred files
    private File mParentPath;
    // Incoming Intent
    private Intent mIntent;
    ...
    /*
     * Called from onNewIntent() for a SINGLE_TOP Activity
     * or onCreate() for a new Activity. For onNewIntent(),
     * remember to call setIntent() to store the most
     * current Intent
     *
     */
    private void handleViewIntent() {
        ...
        // Get the Intent action
        mIntent = getIntent();
        String action = mIntent.getAction();
        /*
         * For ACTION_VIEW, the Activity is being asked to display data.
         * Get the URI.
         */
        if (TextUtils.equals(action, Intent.ACTION_VIEW)) {
            // Get the URI from the Intent
            Uri beamUri = mIntent.getData();
            /*
             * Test for the type of URI, by getting its scheme value
             */
            if (TextUtils.equals(beamUri.getScheme(), "file")) {
                mParentPath = handleFileUri(beamUri);
            } else if (TextUtils.equals(
                    beamUri.getScheme(), "content")) {
                mParentPath = handleContentUri(beamUri);
            }
        }
        ...
    }
    ...
}


从文件URI中获取目录

  如果接收的Intent包含一个文件URI,则该URI包含了一个文件的绝对文件名,包括了完整的路径和文件名。对于Android Beam文件传输来说,目录路径指向了其它传输文件的位置(如果有其它传输文件的话),要获得这个目录路径,要取得URI的路径部分(URI中除去“file:”前缀的部分),根据路径创建一个File对象,然后获取这个File的父目录:

    public String handleFileUri(Uri beamUri) {
        // Get the path part of the URI
        String fileName = beamUri.getPath();
        // Create a File object for this filename
        File copiedFile = new File(fileName);
        // Get a string containing the file's parent directory
        return copiedFile.getParent();
    }


从内容URI获取目录

  如果接收的Intent包含一个内容URI,这个URI可能指向的是一个存储于MediaStore Content Provider的目录和文件名。你可以通过检测URI的authority值来判断是否是MediaStore的内容URI。一个MediaStore的内容URI可能来自Android Beam文件传输也可能来自其它应用,但不管怎么样,你都能根据该内容URI获得一个目录和文件名。
  你也可以接收一个ACTION_VIEW的Intent,它包含有一个content provider的URI,而不是MediaStore,在这种情况下,这个内容URI不包含MediaStore的authority,且这个URI一般不指向一个目录。

  注意:Note:对于Android Beam文件传输,如果第一个接收的文件,其MIME类型为“audio/”,“image/”或者“video/*”,那么你会接收这个在ACTION_VIEW的Intent中的内容URI。Android Beam文件传输会在它存储传输文件的目录内运行Media Scanner,以此为媒体文件添加索引。同时Media Scanner将结果写入MediaStore的content provider,之后它将第一个文件的内容URI回递给Android Beam文件传输。这个内容URI就是你在通知Intent中所接收到的。要获得第一个文件的目录,你需要使用该内容URI从MediaStore中获取它。


指明Content Provider

  为了明确你能从内容URI中获取文件目录,你可以通过调用Uri.getAuthority())获取URI的Authority,以此确定与该URI相关联的Content Provider。其结果有两个可能的值:
  MediaStore.AUTHORITY:表明这个URI关联了被MediaStore追踪的一个文件或者多个文件。可以从MediaStore中获取文件的全名,目录名就自然可以从文件全名中获取。
  其他值:来自其他Content Provider的内容URI。可以显示与该内容URI相关联的数据,但是不要尝试去获取文件目录。

  为了MediaStore的内容URI中获取目录,执行一个查询操作,它将Uri参数指定为收到的内容URI,列名为MediaColumns.DATA。返回的Cursor包含了完整路径和URI所代表的文件名。该目录路径下还包含了由Android Beam文件传输传送到该设备上的其它文件。


  如何测试内容URI的Authority,并获取传输文件的路径和文件名:

...
    public String handleContentUri(Uri beamUri) {
        // Position of the filename in the query Cursor
        int filenameIndex;
        // File object for the filename
        File copiedFile;
        // The filename stored in MediaStore
        String fileName;
        // Test the authority of the URI
        if (!TextUtils.equals(beamUri.getAuthority(), MediaStore.AUTHORITY)) {
            /*
             * Handle content URIs for other content providers
             */
        // For a MediaStore content URI
        } else {
            // Get the column that contains the file name
            String[] projection = { MediaStore.MediaColumns.DATA };
            Cursor pathCursor =
                    getContentResolver().query(beamUri, projection,
                    null, null, null);
            // Check for a valid cursor
            if (pathCursor != null &&
                    pathCursor.moveToFirst()) {
                // Get the column index in the Cursor
                filenameIndex = pathCursor.getColumnIndex(
                        MediaStore.MediaColumns.DATA);
                // Get the full file name including path
                fileName = pathCursor.getString(filenameIndex);
                // Create a File object for the filename
                copiedFile = new File(fileName);
                // Return the parent directory of the file
                return new File(copiedFile.getParent());
             } else {
                // The query didn't work; return null
                return null;
             }
        }
    }
...




您可能感兴趣的与本文相关的镜像

Stable-Diffusion-3.5

Stable-Diffusion-3.5

图片生成
Stable-Diffusion

Stable Diffusion 3.5 (SD 3.5) 是由 Stability AI 推出的新一代文本到图像生成模型,相比 3.0 版本,它提升了图像质量、运行速度和硬件效率

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值