Android NFC技术(三)——初次开发Android NFC你须知道NdefMessage和NdefRecord

这最近也是有好多天没写博客了,除了到处张罗着搬家之外,依旧还是许许多多的琐事阻碍着学习,加上使用NFC开发,也是需要具有NFC功能的测试机,也到买了一个,所以,也说了两天的概念

Android NFC开发(一)——初探NFC,了解当前前沿技术
Android NFC开发(二)——Android世界里的NFC所具备的条件以及使用方法

今天,咋们就来用一个小栗子做药引,一起进入Android NFC开发的世界,首先,你必须要知道的是这两个类

  • NdefMessage
  • NdefRecord

NdefMessage

主要是描述NDEF格式的信息

NdefRecord

这个是秒速NDEF信息的一个信息段

这两个都是Android NCF技术的核心类,无论是读写NFC标签还是通过Android Beam技术传递数据都需要这两个类

开发步骤

1.获取Tag对象

Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

2.判断NFC标签的数格式

Ndef ndef = Ndef.get(tag);

3.写入数据

ndef.wrriteNdefMessage(ndefMessage);

准备工作都做好了,我们就直接来写程序了,我们新建一个程序——NFCDemo

我们的需求是这样的:我们的软件把手机上所有安装好的应用排列,然后我们点击一个就开始拿着这个软件,等我们的NFC标签靠近,就把软件写进去,然后,我们每次只要把NFC标签开进有NFC的手机上就会直接运行我们写入的程序了,这个原理有点儿类似门卡,你的先买一个NFC标签

然后我们就开始写了,大致的情况是这样的,我们主页有一个按钮,点击之后跳转到一个界面,是我们手机安装程序的包名列表,我们选中一个回到主Activity,然后等待NFC标签刷入,成功之后,我们就直接用NFC靠近手机就能启动这个程序了,跟门卡登记,然后开门的道理是一样的

主页是这样的

我们点击之后跳转到ListActivity

ListActivity

package com.lgl.nfcdemo;import android.content.Intent;import android.content.pm.PackageInfo;import android.content.pm.PackageManager;import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import java.util.ArrayList;import java.util.List;/** * 读取手机软件列表 * * @author LGL */public class ListActivity extends android.app.ListActivity implements AdapterView.OnItemClickListener {    //返回码    private static final int CODE = 1;    //封装所有软件    private List<String> mPackage = new ArrayList<String>();    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        //这里继承了ListActivity显示列表,不需要加载layout        //获取手机上所有的包        PackageManager manager = getPackageManager();        //把他们装起来        List<PackageInfo> packageInfos = manager.getInstalledPackages(PackageManager.GET_ACTIVITIES);        //遍历        for (PackageInfo pi : packageInfos) {            //添加软件名和包名            mPackage.add(pi.applicationInfo.loadLabel(manager) + "\n" + pi.packageName);        }        //官方的适配器        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, mPackage);        setListAdapter(arrayAdapter);        //设置单击事件        getListView().setOnItemClickListener(this);    }    @Override    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {        Intent intent = new Intent();        intent.putExtra("package", mPackage.get(i));        setResult(CODE,intent);        finish();    }}

这段代码应该清晰易懂吧,继承lListActivity,获取手机的应用排列,点击之后携带包名finish();

MainActivity

package com.lgl.nfcdemo;import android.app.PendingIntent;import android.content.Intent;import android.nfc.FormatException;import android.nfc.NdefMessage;import android.nfc.NdefRecord;import android.nfc.NfcAdapter;import android.nfc.Tag;import android.nfc.tech.Ndef;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.google.android.gms.common.api.GoogleApiClient;import java.io.IOException;/** * NFC读写 * Created by lgl on 16/3/1. */public class MainActivity extends AppCompatActivity {    private Button btn_list;    //选中的包名    private String mPackNmae;    private NfcAdapter mNfcAdapter;    private PendingIntent mPendingIntent;    private GoogleApiClient client;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        btn_list = (Button) findViewById(R.id.btn_list);        //初始化NfcAdapter        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);        //初始化PendingIntent        mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()), 0);        //点击跳转        btn_list = (Button) findViewById(R.id.btn_list);        btn_list.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View view) {                Intent intent = new Intent(MainActivity.this,ListActivity.class);                startActivityForResult(intent,1);            }        });    }    //当设置android:launchMode="singleTop"时调用    @Override    protected void onNewIntent(Intent intent) {        super.onNewIntent(intent);        //没有选择的话就不执行操作了        if (mPackNmae == null) {            return;        }        //1.获取Tag对象        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);        //写入程序        writeNFC(tag);    }    //NFC写入    private void writeNFC(Tag tag) {        //null不执行操作,强调写程序的逻辑性        if (tag == null) {            return;        }        NdefMessage ndefMessage = new NdefMessage(new NdefRecord[]{NdefRecord.createApplicationRecord(mPackNmae)});        //获得写入大小        int size = ndefMessage.toByteArray().length;        //2.判断是否是NDEF标签            try {                Ndef ndef = Ndef.get(tag);                if(ndef != null) {                    //说明是NDEF标签,开始连接                    ndef.connect();                    //判断是否可写                    if(!ndef.isWritable()){                        Toast.makeText(this, "当前设备不支持写入",Toast.LENGTH_LONG).show();                        return;                    }                    //判断大小                    if(ndef.getMaxSize() < size){                        Toast.makeText(this, "容量太小了",Toast.LENGTH_LONG).show();                        return;                    }                    //写入                    try {                        ndef.writeNdefMessage(ndefMessage);                        Toast.makeText(this, "写入成功",Toast.LENGTH_LONG).show();                    } catch (FormatException e) {                        e.printStackTrace();                    }                }            } catch (IOException e) {                e.printStackTrace();        }    }    //使当前窗口置顶,权限高于三重过滤    @Override    protected void onResume() {        super.onResume();        if (mNfcAdapter != null) {            //设置当前activity为栈顶            mNfcAdapter.enableForegroundDispatch(this, mPendingIntent, null, null);        }    }    @Override    protected void onPause() {        super.onPause();        //恢复栈        if (mNfcAdapter != null) {            mNfcAdapter.disableForegroundDispatch(this);        }    }}

这里东西多了点,不过仔细看会发现,也就是一些判断,真正的关键代码就那几句,

layout_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" android:orientation="vertical">    <Button  android:layout_marginTop="15dp" android:id="@+id/btn_list" android:layout_width="200dp" android:layout_height="45dp" android:text="绑定应用程序" android:layout_gravity="center_horizontal" />    <TextView  android:gravity="center_horizontal" android:textSize="14sp" android:text="你可以将NFC标签靠近手机背部" android:layout_width="match_parent" android:layout_height="wrap_content" />    <ImageView  android:layout_weight="1" android:background="@mipmap/nfc" android:layout_width="match_parent" android:layout_height="0dp" /></LinearLayout>

我们来简单的运行一下

然后我们靠近NFC就算写入成功了,以后我们只要拿着NFC靠近手机就自动打开我们写入的那个程序了,原理和门卡有点类似,下节接着讲NFC和网络交互的那些事

Demo下载:待上传

更多相关文章

  1. mybatisplus的坑 insert标签insert into select无参数问题的解决
  2. C#/mono开发Android应用程序入门(三)-平台的意义和思考
  3. Android(安卓)视频开发浅析
  4. 【Android】蓝牙开发——BLE(低功耗蓝牙)(附完整Demo)
  5. Xamarin For Visual Studio 3.0.54.0 完整离线破解版(C# 开发Andr
  6. Android开发笔记(三十四)Excel文件的读写
  7. 成为更好的Android开发者的30多个技巧
  8. Google Android(安卓)SDK开发范例大全 下载
  9. 【Android开发】Android(安卓)Host详解(翻译自官方文档)

随机推荐

  1. Android-View-Attribute
  2. Android 中.aar文件生成方法与用法
  3. android:configChanges问题
  4. android 类似QQ 换皮肤 实现思路 apk资源
  5. Android系统底层架构【译】
  6. Android中用Application类实现全局变量
  7. Android MediaPlayer学习笔记
  8. [置顶] Android--纠正Activity横竖屏切换
  9. Android开发中高效的数据结构用SparseArr
  10. 使用NanoHttpd在Android上实现HttpServer