将NFC触发器应用于基本计时器应用程序(Android)的最简单方法

将NFC触发器应用于基本计时器应用程序(Android)的最简单方法,android,nfc,Android,Nfc,我有一个基本的倒计时应用程序,当点击按钮时从10秒开始倒计时。当接触特定NFC标签时,启动计时器的最简单方法是什么?(NTAG203) 我已经阅读了好几本NFC教程,唯一一本我能够开始工作的是一个简单的标签阅读器。如果我想让一个特定的NFC标签触发一个简单的计时器应用程序,就像按钮一样,我该怎么做呢?最好是读取ID还是将纯文本解释为标识符 谢谢(使用Android Studio) NFC应用程序主要活动(代码取自本教程: package com.example.nfctest2.nfctest2

我有一个基本的倒计时应用程序,当点击按钮时从10秒开始倒计时。当接触特定NFC标签时,启动计时器的最简单方法是什么?(NTAG203)

我已经阅读了好几本NFC教程,唯一一本我能够开始工作的是一个简单的标签阅读器。如果我想让一个特定的NFC标签触发一个简单的计时器应用程序,就像按钮一样,我该怎么做呢?最好是读取ID还是将纯文本解释为标识符

谢谢(使用Android Studio)

NFC应用程序主要活动(代码取自本教程:

package com.example.nfctest2.nfctest2app;
导入java.io.UnsupportedEncodingException;
导入java.util.array;
导入android.app.Activity;
导入android.app.pendingent;
导入android.content.Intent;
导入android.content.IntentFilter;
导入android.content.IntentFilter.MalformedMimeTypeException;
导入android.nfc.NdefMessage;
导入android.nfc.NdefRecord;
导入android.nfc.NfcAdapter;
导入android.nfc.Tag;
导入android.nfc.tech.Ndef;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动{
公共静态最终字符串MIMETYPE\u TEXT\u PLAIN=“TEXT/PLAIN”;
公共静态最终字符串TAG=“NfcTut”;
私有文本视图tV_ReadNFC;
私人NfcAdapter nfcAdapt;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
tV_ReadNFC=(TextView)findviewbyd(R.id.tV_ReadNFC);
//初始化nfc适配器
nfcAdapt=NfcAdapter.getDefaultAdapter(此);
//当设备不支持NFC时,检查NFC适配器是否初始化为null
如果(nfcAdapt==null){
//设备不支持nfc
Toast.makeText(这是“您的设备不支持NFC.”,Toast.LENGTH_SHORT.show();
完成();
返回;
}
//检查是否启用了NFC适配器功能
如果(!nfcAdapt.isEnabled()){
tV_ReadNFC.setText(“NFC已禁用”);
}否则{
tV_ReadNFC.setText(R.string.attachNFCToRead);
}
handleIntent(getIntent());
}
@凌驾
受保护的void onResume(){
super.onResume();
}
@凌驾
受保护的void onPause(){
//在onPause之前调用此选项,以避免出现IllegalArgumentException。
stopForegroundDispatch(本,nfcAdapt);
super.onPause();
}
@凌驾
受保护的void onNewIntent(意图){
手册内容(意图);
}
私人无效手册内容(意图){
//从意图中获得行动
String action=intent.getAction();
//是否操作与发现的NDEF\u匹配
if(NfcAdapter.ACTION\u NDEF\u DISCOVERED.equals(ACTION)){
//什么是mime类型
字符串类型=intent.getType();
//文本是否为纯文本
if(MIMETYPE_TEXT_PLAIN.equals(type)){
//创建标记实例并从intent检索扩展数据
Tag Tag=intent.getParcelableExtra(NfcAdapter.EXTRA_Tag);
//执行后台任务
新建NdefReaderBgTask().execute(标记);
}否则{
Log.d(标记“mime类型不是文本/纯文本:”+type);
}
}
//动作是否与所发现的动作匹配
else if(NfcAdapter.ACTION\u TECH\u DISCOVERED.equals(ACTION)){
//以防我们仍然使用这项技术
Tag Tag=intent.getParcelableExtra(NfcAdapter.EXTRA_Tag);
//获取可用的技术
String[]techList=tag.getTechList();
//获取类名
字符串searchedTech=Ndef.class.getName();
用于(字符串技术:技术列表){
//标记匹配,然后执行后台任务
如果(搜索技术等于(技术)){
新建NdefReaderBgTask().execute(标记);
打破
}
}
}
}
/**
*@param代理相应的{@link Activity}请求前台调度。
*@param adp用于前台调度的{@link NfcAdapter}。
*/
公共静态无效请求ForeGroundDispatch(最终活动法案,NfcAdapter adp){
//创建意图实例
最终意图=新意图(act.getApplicationContext(),act.getClass());
//在顶部设置旗帜
intent.setFlags(intent.FLAG\u ACTIVITY\u SINGLE\u TOP);
//挂起意图的板条箱实例
final pendingent pendingent=pendingent.getActivity(act.getApplicationContext(),0,intent,0);
//创建意图过滤器阵列
IntentFilter[]过滤器=新的IntentFilter[1];
//创建techlist字符串的二维数组
字符串[][]技术列表=新字符串[][]{};
//注意:这与清单中的筛选器相同。
过滤器[0]=新的IntentFilter();
筛选器[0].addAction(发现NfcAdapter.ACTION\u NDEF\u);
筛选器[0].addCategory(Intent.CATEGORY\u默认值);
试一试{
//添加数据类型
筛选器[0]。addDataType(MIMETYPE\u TEXT\u PLAIN);
}捕获(格式错误的dmimetype异常){
//在不同的mime类型上引发异常
抛出新的RuntimeException(“检查mime类型”);
}
//启用对当前活动的前台分派
adp.enableForegroundDispatch(act、PendingEvent、过滤器、技术列表);
}
公共静态无效stopForegroundDispatch(最终活动法案,NfcAdapter adp){
adp.disableForegroundDispatch(act);
}
私有类NdefReaderBgTask扩展了AsyncTask{
@凌驾
受保护的字符串doInBackground(标记…参数){
Tag Tag=params[0];
Ndef Ndef=Ndef.get(标签);
如果(ndef==null){
//当此标记不支持NDEF时。
返回null;
}
//获取在发现时从标记读取的NdefMessage。
NdefMessage NdefMessage=ndef.getCachedNdefMessage();
//得到t
    package com.example.nfctest2.nfctest2app;

    import java.io.UnsupportedEncodingException;
    import java.util.Arrays;
    import android.app.Activity;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.content.IntentFilter.MalformedMimeTypeException;
    import android.nfc.NdefMessage;
    import android.nfc.NdefRecord;
    import android.nfc.NfcAdapter;
    import android.nfc.Tag;
    import android.nfc.tech.Ndef;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.widget.TextView;
    import android.widget.Toast;

public class MainActivity extends Activity {

public static final String MIMETYPE_TEXT_PLAIN = "text/plain";
public static final String TAG = "NfcTut";

private TextView tV_ReadNFC;
private NfcAdapter nfcAdapt;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    //initialize control
    tV_ReadNFC = (TextView) findViewById(R.id.tV_ReadNFC);
    //initialise nfc adapter
    nfcAdapt = NfcAdapter.getDefaultAdapter(this);
    //check is NFC adapter initialized null when device doesn't support NFC
    if (nfcAdapt == null) {
        // device deosn't support nfc
        Toast.makeText(this, "your device doesn't support NFC.",      Toast.LENGTH_SHORT).show();
        finish();
        return;
    }
    //check is NFC adapter feature enabled
    if (!nfcAdapt.isEnabled()) {
        tV_ReadNFC.setText("NFC is disabled.");
    } else {
        tV_ReadNFC.setText(R.string.attachNFCToRead);
    }
    handleIntent(getIntent());
}

@Override
protected void onResume() {
    super.onResume();

}

@Override
protected void onPause() {

    //Call this before onPause, to avoid an IllegalArgumentException.
    stopForegroundDispatch(this, nfcAdapt);
    super.onPause();
}

@Override
protected void onNewIntent(Intent intent) {

    handleIntent(intent);
}

private void handleIntent(Intent intent) {
    //get action from intent
    String action = intent.getAction();
    //is action matches the NDEF_DISCOVERED
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
        //what is the mime type
        String type = intent.getType();
        //is text plain or not
        if (MIMETYPE_TEXT_PLAIN.equals(type)) {
            //create tag instance and retrieve extended data from intent
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            //execute background task
            new NdefReaderBgTask().execute(tag);

        } else {
            Log.d(TAG, "mime type is not text/plain: " + type);
        }
    }
    //is action matches the ACTION_TECH_DISCOVERED
    else if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {

        // In case we would still use the Tech Discovered Intent
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //get the available technologies
        String[] techList = tag.getTechList();
        //get class name
        String searchedTech = Ndef.class.getName();

        for (String tech : techList) {
            //tag matched then execute background task
            if (searchedTech.equals(tech)) {
                new NdefReaderBgTask().execute(tag);
                break;
            }
        }
    }
}

/**
 * @param act The corresponding {@link Activity} requesting the foreground dispatch.
 * @param adp The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void requestForegroundDispatch(final Activity act, NfcAdapter adp) {
    //create instance of intent
    final Intent intent = new Intent(act.getApplicationContext(), act.getClass());
    //set flags on top
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    //crate instance of pending intent
    final PendingIntent pendingIntent = PendingIntent.getActivity(act.getApplicationContext(), 0, intent, 0);
    //create intent filters array
    IntentFilter[] filters = new IntentFilter[1];
    //create 2D array of techlist String
    String[][] techList = new String[][]{};

    // Note: This is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    try {
        //add data type
        filters[0].addDataType(MIMETYPE_TEXT_PLAIN);
    } catch (MalformedMimeTypeException e) {
        //throw exception on different mime type
        throw new RuntimeException("Check your mime type.");
    }
    //enable foreground dispatch to current activity
    adp.enableForegroundDispatch(act, pendingIntent, filters, techList);
}


public static void stopForegroundDispatch(final Activity act, NfcAdapter adp) {
    adp.disableForegroundDispatch(act);
}


private class NdefReaderBgTask extends AsyncTask<Tag, Void, String> {

    @Override
    protected String doInBackground(Tag... params) {
        Tag tag = params[0];

        Ndef ndef = Ndef.get(tag);
        if (ndef == null) {
            // when NDEF is not supported by this Tag.
            return null;
        }
        //Get the NdefMessage that was read from the tag at discovery time.
        NdefMessage ndefMessage = ndef.getCachedNdefMessage();
        //Get the NDEF Records inside this NDEF Message.
        NdefRecord[] records = ndefMessage.getRecords();
        for (NdefRecord ndefRecord : records) {
            if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                try {
                    return readNDEFRecordText(ndefRecord);
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "Unsupported Encoding", e);
                }
            }
        }

        return null;
    }

    private String readNDEFRecordText(NdefRecord record) throws UnsupportedEncodingException {

        // get record pay load variable length
        byte[] payload = record.getPayload();

        // Get the Text Encoding
        String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";

        // Get the Language Code
        int languageCodeLength = payload[0] & 0063;

        // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
        // e.g. "en"

        // Get the Text
        return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
    }

    @Override
    protected void onPostExecute(String result) {
        if (result != null) {
            tV_ReadNFC.setText("Content in your TAG: " + result);
        }
    }
}
    }
public static void requestForegroundDispatch(final Activity act, NfcAdapter adp) {
    final Intent pendingIntent = PendingIntent.getActivity(act, 0, new Intent(act, act.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    IntentFilter[] filters = new IntentFilter[] { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };
    String[][] techList = new String[][] { new String[] { NfcA.class.getName() } };

    adp.enableForegroundDispatch(act, pendingIntent, filters, techList);
}
private void handleIntent(Intent intent) {
    String action = intent.getAction();
    if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
        Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] id = tag.getId();

        // do something with the ID
    }
}