早上好,我想使用我在页面上找到的写法: https://developer.android.com/guide/topics/connectivity/nfc/advanced-nfc.html,写一个超轻的mifare.我还没有成功.
public void writeTag(Tag tag,String tagText) {
   mifareUltralight ultralight = mifareUltralight.get(tag);
   try {
      ultralight.connect();
      ultralight.writePage(4,"abcd".getBytes(Charset.forName("US-ASCII")));
      ultralight.writePage(5,"efgh".getBytes(Charset.forName("US-ASCII")));
      ultralight.writePage(6,"ijkl".getBytes(Charset.forName("US-ASCII")));
      ultralight.writePage(7,"mnop".getBytes(Charset.forName("US-ASCII")));
   } catch (IOException e) {
      Log.e(TAG,"IOException while closing mifareUltralight...",e);
   } finally {
       try {
          ultralight.close();
       } catch (IOException e) {
          Log.e(TAG,e);
       }
   }
}

我如何从主打电话给它?

我认为有必要插入一个按钮来检查标签是否存在.

我在我的活动(不是主要活动)中添加了“前台调度系统”,但是我仍然不明白如果标签存在与否,如何显示消息,在使用读写方法之前要检查什么?

package com.example.administrator.myapplication3;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.mifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.IOException;
import java.nio.charset.Charset;

public class displayMessageActivity extends AppCompatActivity {

    private NfcAdapter mAdapter;
    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String[][] mTechLists;

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // Capture the layout's TextView and set the string as its text
        TextView textView = (TextView) findViewById(R.id.textView);
        textView.setText(message);

        pendingIntent = PendingIntent.getActivity( this,new Intent(this,getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);

        mAdapter = NfcAdapter.getDefaultAdapter(this);
        pendingIntent = PendingIntent.getActivity(
                this,0);

        // Setup an intent filter for all MIME based dispatches
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_disCOVERED);
        try {
            ndef.addDataType("*/*");
        } catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail",e);
        }
        IntentFilter td = new IntentFilter(NfcAdapter.ACTION_TAG_disCOVERED);
        mFilters = new IntentFilter[] {
                ndef,td
        };

        // Setup a tech list for all NfcF tags
        mTechLists = new String[][] { new String[] { mifareUltralight.class.getName(),Ndef.class.getName(),NfcA.class.getName()}};


        Button b = (Button) findViewById(R.id.button2);
        b.setonClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TextView tv = (TextView) findViewById(R.id.textView);

               Tag tag = getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
                tv.setText("Click!");

                //byte[] x=tag.getId();
                writeTag(tag,"x");
                Log.e(TAG,"cc");



            }
        });

    }

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

        mAdapter.enableForegrounddispatch(this,pendingIntent,mFilters,mTechLists);
    }

    @Override
    public void onPause()
    {
        super.onPause();
        mAdapter.disableForegrounddispatch(this);
    }

    @Override
    public void onNewIntent(Intent intent){

        // fetch the tag from the intent
        Tag t = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

       // String tlist = getTechList(t);
       // android.util.Log.v("NFC","discovered tag ["+tlist+"]["+t+"] with intent: " + intent);
       // android.util.Log.v("NFC","{"+t+"}");
    }





    public void writeTag(Tag tag,String tagText) {
        mifareUltralight ultralight = mifareUltralight.get(tag);
        try {
            ultralight.connect();
            ultralight.writePage(4,"abcd".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(5,"efgh".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(6,"ijkl".getBytes(Charset.forName("US-ASCII")));
            ultralight.writePage(7,"mnop".getBytes(Charset.forName("US-ASCII")));
        } catch (IOException e) {
            Log.e(TAG,e);
        } finally {
            try {
                ultralight.close();
            } catch (IOException e) {
                Log.e(TAG,e);
            }
        }
    }

    public String readTag(Tag tag) {
        mifareUltralight mifare = mifareUltralight.get(tag);
        try {
            mifare.connect();
            byte[] payload = mifare.readPages(4);
            return new String(payload,Charset.forName("US-ASCII"));
        } catch (IOException e) {
            Log.e(TAG,"IOException while writing mifareUltralight message...",e);
        } finally {
            if (mifare != null) {
                try {
                    mifare.close();
                }
                catch (IOException e) {
                    Log.e(TAG,"Error closing tag...",e);
                }
            }
        }
        return null;
    }
}

谢谢!

解决方法

扫描新的NFC标签后立即调用onNewIntent(Intent intent).例如,如果您想要写入每个扫描的标记,则onNewIntent()方法将如下所示:
//This method is called whenever a new tag is scanned while the activity is running
//Whatever you want to do with scanned tags,do it in here
@Override
public void onNewIntent(Intent intent){
    // fetch the tag from the intent
    Tag tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

    //Write a String onto the tag
    writeTag(tag,"Put any string here");
}

你的writeTag方法当然还没有使用它给出的字符串,但你可能知道.

如果您想要保持最新的布尔值以检查可用标记,请执行以下操作:

@Override
 public void onNewIntent(Intent intent){

     (new Thread(new Runnable() {
         @Override
         public void run() {
             // fetch the tag from the intent
             Tag tag = (Tag)intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
             mifareUltralight mytag = mifareUltralight.get(tag);
             /* Alternative to mifareUltralight:
             NfcA mytag = NfcA.get(tag);
             */
             mytag.connect();
             while(true){
                 //someBoolean is just a Boolean that you can use in other threads to ask if tag is still there
                 someBoolean = true;
                 //Keep reading the tag until it ends in an exception
                 //when the exception occurs,you kNow the tag is gone
                 try{
                     mytag.transceive(new byte[] {
                          (byte) 0xXX,// READ command for your tag here
                          (byte) 0xXX,// Address of serial or UID field of your tag here
                     });
                  }catch(IOException e){
                      mytag.disconnect();
                      break;
                  }
              }
              //When loop breaks,the tag is gone,so we  set the variable back to false
              someBoolean = false;
          }
      })).start();
 }

android – 如何知道标签是否存在?的更多相关文章

  1. 确定字符串是否包含Swift中的一个字符的最佳方法是什么?

    我需要确定字符串是否包含我定义的自定义集中的任何字符.我从this发现你可以使用rangeOfString来确定一个字符串是否包含另一个字符串.这当然也适用于字符,如果你一次测试每个字符一个.我想知道最好的办法是做什么.您可以创建一个包含自定义字符集的CharacterSet然后根据此字符集测试成员资格:Swift3:对于不区分大小写的比较,请使用.Swift2:Swift1.2

  2. 在手机在Android中睡觉时处理NFC

    我想知道手机睡觉时是否可以处理NFC?似乎没有意图启动,所以我想系统关闭了nfc?解决方法不会.当设备的显示屏关闭时,不会生成和发送意图.如果您有NexusS,请尝试标记某些内容并观察catlog,您将在手机上找不到任何内容.我认为这种行为非常合理.从今天起,我们周围的许多东西都有RFID标签,如果即使屏幕关闭也可以触发NFC应用程序,可能会发生意外情况.

  3. android – nexus的NFC / RFID入门

    NexusSNFC/RFID入门.有人可以提供任何指导吗?我有兴趣使用nexus的NFC/RFID硬件创建一些家庭酿造演示.我想我需要找到合适的标签,以及如何将网址编码为nexus可以通过它的标签应用程序读取的标签.不确定iso14443标签或mifare等nexus是否支持所有libnfc?如果我root设备可以访问写入功能吗?v=eu7fQsPjDls).该URL是使用其他设备编写的.

  4. android – 我的应用程序如何找出启用了哪种NFC模式?

    我发现Android设备支持三种NFC模式:读写器,P2P和卡模拟.我的应用程序可以检查当前启用的模式吗?

  5. android – 如何将外部NFC读卡器连接到平板电脑

    现在我正在使用平板电脑安装操作系统Android2.3.3而不是NFC手机,所以我需要将外部读卡器连接到平板电脑.请告诉我我应该选择哪种读卡器以及将读卡器连接到平板电脑所需的任何驱动程序.内置的NFC库是否支持该读卡器?提前致谢.解决方法我找到了答案,ACS现在为他们的读者提供了android库和示例应用程序.你可以找到库here和android支持的读者的一些信息和视频演示是here.唯一的问题是ACS安卓库只支持Android3.1及以上版本.希望它能帮助你.如果您还有问题请随时询问..

  6. android – 使用改造下载图像文件

    解决方法问题是响应中的内容类型标头包含一个虚假的字符集:Retrofit看到了这一点,并推断响应是它可以记录的文本.您应该将问题报告给服务器的管理员.如果您将问题报告给GitHub上的Retrofit问题跟踪器,我们可能会从此问题中恢复而不是崩溃.

  7. android – enableReaderMode和enableForegroundDispatch有什么区别?

    我找到了两种让Android应用检测和处理NFC标签的方法:>NfcAdapter.enableReaderMode(活动,回调,标志,附加组件),然后在回调中接收标签信息.>NfcAdapter.enableForegrounddispatch(activity,intent,filters,techLists)然后在onNewIntent(intent)活动方法中接收标记信息.我目前使用第二种

  8. android – 如何知道标签是否存在?

    我认为有必要插入一个按钮来检查标签是否存在.我在我的活动中添加了“前台调度系统”,但是我仍然不明白如果标签存在与否,如何显示消息,在使用读写方法之前要检查什么?解决方法扫描新的NFC标签后立即调用onNewIntent.例如,如果您想要写入每个扫描的标记,则onNewIntent()方法将如下所示:你的writeTag方法当然还没有使用它给出的字符串,但你可能知道.如果您想要保持最新的布尔值以检查可用标记,请执行以下操作:

  9. android – NfcAdapter.getDefaultAdapter(this)在模拟器中返回null

    解决方法你真的不能对模拟器和NFC做任何有趣的事情.您不希望使用TAG_disCOVERED操作,因为这是最后的操作.在真实设备上生成的意图不能像在NFCDemo演示中那样伪造.在2.3.3中更好地支持NFC之前,NFCDemo以2.3发布.这太糟糕了.也许未来会有一些选择,但现在我们都不得不购买具备NFC功能的NFC设备.

  10. android – 是否可以从React App访问NFC功能

    我将使用ReactNative为Android构建一个应用程序,我很想知道我是否可以访问NFC功能.我可以看到与Cordova相关的东西,但就我对原生移动网络应用程序的新手而言,我想进一步搜索.谢谢你的时间.解决方法我们最近在GitHub上发布了react-native-nfc.该项目的目标是支持ReactNative中的NFC操作.

随机推荐

  1. bluetooth-lowenergy – Altbeacon库无法在Android 5.0上运行

    昨天我在Nexus4上获得了Android5.0的更新,并且altbeacon库停止了检测信标.似乎在监视和测距时,didEnterRegion和didRangeBeaconsInRegion都没有被调用.即使RadiusNetworks的Locate应用程序现在表现不同,一旦检测到信标的值,它们就不再得到更新,并且通常看起来好像信标超出了范围.我注意到的一点是,现在在logcat中出现以下行“B

  2. android – react-native动态更改响应者

    我正在使用react-native进行Android开发.我有一个视图,如果用户长按,我想显示一个可以拖动的动画视图.我可以使用PanResponder实现这一点,它工作正常.但我想要做的是当用户长按时,用户应该能够继续相同的触摸/按下并拖动新显示的Animated.View.如果您熟悉Google云端硬盘应用,则它具有类似的功能.当用户长按列表中的任何项目时,它会显示可拖动的项目.用户可以直接拖

  3. android – 是否有可能通过使用与最初使用的证书不同的证书对其进行签名来发布更新的应用程序

    是否可以通过使用与最初使用的证书不同的证书进行签名来发布Android应用程序的更新?我知道当我们尝试将这样的构建上传到市场时,它通常会给出错误消息.但有没有任何出路,比如将其标记为主要版本,指定市场中的某个地方?解决方法不,你不能这样做.证书是一种工具,可确保您是首次上传应用程序的人.所以总是备份密钥库!

  4. 如何检测Android中是否存在麦克风?

    ..所以我想在让用户访问语音输入功能之前检测麦克风是否存在.如何检测设备上是否有麦克风.谢谢.解决方法AndroidAPI参考:hasSystemFeature

  5. Android – 调用GONE然后VISIBLE使视图显示在错误的位置

    我有两个视图,A和B,视图A在视图B上方.当我以编程方式将视图A设置为GONE时,它将消失,并且它正下方的视图将转到视图A的位置.但是,当我再次将相同的视图设置为VISIBLE时,它会在视图B上显示.我不希望这样.我希望视图B回到原来的位置,这是我认为会发生的事情.我怎样才能做到这一点?编辑–代码}这里是XML:解决方法您可以尝试将两个视图放在RelativeLayout中并相对于彼此设置它们的位置.

  6. android – 获得一首歌的流派

    我如何阅读与歌曲相关的流派?我可以读这首歌,但是如何抓住这首歌的流派,它存放在哪里?解决方法检查此代码:

  7. android – 使用textShadow折叠工具栏

    我有一个折叠工具栏的问题,在展开状态我想在文本下面有一个模糊的阴影,我使用这段代码:用:我可以更改textColor,它可以工作,但阴影不起作用.我为阴影尝试了很多不同的值.是否可以为折叠文本投射阴影?

  8. android – 重用arm共享库

    我已经建立了armarm共享库.我有兴趣重用一个函数.我想调用该函数并获得返回值.有可能做这样的事吗?我没有任何头文件.我试过这个Android.mk,我把libtest.so放在/jni和/libs/armeabi,/lib/armeabi中.此时我的cpp文件编译,但现在是什么?我从objdump知道它的名字编辑:我试图用这个android.mk从hello-jni示例中添加prebuild库:它工作,但libtest.so相同的代码显示以下错误(启动时)libtest.so存在于libhello-j

  9. android – 为NumberPicker捕获键盘’Done’

    我有一个AlertDialog只有一些文本,一个NumberPicker,一个OK和一个取消.(我知道,这个对话框还没有做它应该保留暂停和恢复状态的事情.)我想在软键盘或其他IME上执行“完成”操作来关闭对话框,就像按下了“OK”一样,因为只有一个小部件可以编辑.看起来处理IME“Done”的最佳方法通常是在TextView上使用setonEditorActionListener.但我没有任何Te

  10. android – 想要在调用WebChromeClient#onCreateWindow时知道目标URL

    当我点击一个带有target=“_blank”属性的超链接时,会调用WebChromeClient#onCreateWindow,但我找不到新的窗口将打开的新方法?主页url是我唯一能知道的东西?我想根据目标网址更改应用行为.任何帮助表示赞赏,谢谢!

返回
顶部