从NFC标签自动读取数据 [英] Automatically Reading data from NFC Tag

查看:91
本文介绍了从NFC标签自动读取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我想读的NFC标签的数据。塔数据读取使用没有问题。但我必须扫描我的标签两次来显示数据。当我扫描标签中的第一次启动应用程序,但不读取数据。因此,要读取数据我要再次扫描我的标签。所以,我该怎么办,这样,只要我扫描我的标签应该启动应用程序,以及从标签读取数据。该应用程序是从标签读取数据,并改变了我的android手机的配置文件。这是我的code .. 谢谢....

 公共类阅读延伸活动{

    标签detectedTag;
    TextView的txtType,txtSize,txtWrite,txtRead;
    按钮btn_back;
    NfcAdapter nfcAdapter;
    IntentFilter的[] readTagFilters;
    PendingIntent pendingIntent;
    byte []的new_payload;

    @覆盖
    保护无效的onCreate(包savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        的setContentView(R.layout.read);
        。getWindow()setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);

         nfcAdapter = NfcAdapter.getDefaultAdapter();
         detectedTag = getIntent()getParcelableExtra(NfcAdapter.EXTRA_TAG)。
        txtType =(TextView中)findViewById(R.id.txtType);
        txtSize =(TextView中)findViewById(R.id.txtsize);
        txtRead =(TextView中)findViewById(R.id.txt_read);

        pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,
                新的意图(这一点,的getClass())。
                addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);

        IntentFilter的tagDetected =新的IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter的过滤器2 =新的IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        readTagFilters =新的IntentFilter [] {tagDetected,过滤器2};


        btn_back =(按钮)findViewById(R.id.btn_back);

        btn_back.setOnClickListener(新View.OnClickListener(){

            @覆盖
            公共无效的onClick(视图v){
                意图I =新的意图(getApplicationContext(),NFCTagWriterActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(ⅰ);

            }
        });
    }

    @覆盖
    保护无效onNewIntent(意向意图){
        // TODO自动生成方法存根

        setIntent(意向);
        如果(getIntent()的getAction()。等于(NfcAdapter.ACTION_TAG_DISCOVERED)){
            detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            readFromTag(getIntent());
        }

        其他{
            AlertDialog.Builder建设者=新AlertDialog.Builder(getApplicationContext());
            builder.setMessage(标签未检测到!请把标签接近)。setCancelable(假).setPositiveButton(OK,新DialogInterface.OnClickListener(){

                @覆盖
                公共无效的onClick(DialogInterface对话,诠释它){
                    // TODO自动生成方法存根

                }
            })。显示();

            AlertDialog警报= builder.create();
            Toast.makeText(getApplicationContext(),无标签检测到,Toast.LENGTH_LONG).show();
        }

    }


    @覆盖
    保护无效onResume(){
        // TODO自动生成方法存根
        super.onResume();
        nfcAdapter.enableForegroundDispatch(这一点,pendingIntent,readTagFilters,NULL);
    }


    公共无效readFromTag(意向意图){

        NDEF NDEF = Ndef.get(detectedTag);


        尝试{
            ndef.connect();

            txtType.setText(ndef.getType()的toString());
            txtSize.setText(将String.valueOf(ndef.getMaxSize()));

            Parcelable []消息= intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            如果(消息!= NULL){
                NdefMessage [] ndefMessages =新NdefMessage [messages.length]
                的for(int i = 0; I< messages.length;我++){
                    ndefMessages [I] =(NdefMessage)消息[I]
                }
            NdefRecord记录= ndefMessages [0] .getRecords()[0];

            byte []的有效载荷= record.getPayload();
            INT长度= payload.length;

            new_payload =新的字节[长度为3]。
            System.arraycopy(有效载荷,3,new_payload,0,长度-3);

            字符串文本=新的String(new_payload);

            txtRead.setText(文本);
            Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_LONG).show();

            如果(text.equalsIgnoreCase(沉默)){
                Toast.makeText(getApplicationContext(),文本,Toast.LENGTH_LONG).show();
                AudioManager audiomanage =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            }
            如果(text.equalsIgnoreCase(颤动)){
                AudioManager audiomanage =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
            }
            如果(text.equalsIgnoreCase(正常)){
                AudioManager audiomanage =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
            }

            ndef.close();

        }
        }
        赶上(例外五){
            Toast.makeText(getApplicationContext(),e.​​toString(),Toast.LENGTH_LONG).show();
        }
    }
}
 

解决方案

现在的问题是,onNewIntent心不是叫onCreate方法。快速的解决方案,脑海中出现:

在onCreate方法,你可以chceck的意图类型。如果它是一个标签为探索,你处理它只是同样的方式在onNewIntent。

另一种解决方案是将处理code在onResume(如果标签雷丁是所有的应用程序那样),检查意图那里。

也许有更清洁的解决方案,病了以后给它一些想法,但现在,这应该帮助你。

Hi I am trying to read data from NFC Tag. Tha data is read no problem with that. But I have to scan my Tag two times to display data. The first time when I scan tag it initiates the application but does not read the data. So to read data I have to again scan my tag. So what should I do so that as soon as I scan my Tag it should initiate the application as well as read data from the tag. The application is to read data from the tag and change the profile of my android phone. Here is my code.. Thank You....

public class Read extends Activity {

    Tag detectedTag;
    TextView txtType,txtSize,txtWrite,txtRead;
    Button btn_back;
    NfcAdapter nfcAdapter;
    IntentFilter[] readTagFilters;
    PendingIntent pendingIntent;
    byte[] new_payload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.read);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

         nfcAdapter = NfcAdapter.getDefaultAdapter();
         detectedTag =getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
        txtType  = (TextView) findViewById(R.id.txtType);
        txtSize  = (TextView) findViewById(R.id.txtsize);
        txtRead  = (TextView) findViewById(R.id.txt_read);

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

        IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
        IntentFilter filter2     = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        readTagFilters = new IntentFilter[]{tagDetected,filter2};


        btn_back = (Button) findViewById(R.id.btn_back);

        btn_back.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(getApplicationContext(),NFCTagWriterActivity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(i);

            }
        });
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub

        setIntent(intent); 
        if(getIntent().getAction().equals(NfcAdapter.ACTION_TAG_DISCOVERED)){
            detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

            readFromTag(getIntent());
        }

        else{
            AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
            builder.setMessage("Tag Not Detected! Please Bring Tag In Proximity").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // TODO Auto-generated method stub

                }
            }).show();

            AlertDialog alert = builder.create();
            Toast.makeText(getApplicationContext(), "No Tag Detected", Toast.LENGTH_LONG).show();
        }

    }


    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        nfcAdapter.enableForegroundDispatch(this, pendingIntent, readTagFilters, null);
    }


    public void readFromTag(Intent intent){

        Ndef ndef = Ndef.get(detectedTag);


        try{
            ndef.connect();

            txtType.setText(ndef.getType().toString());
            txtSize.setText(String.valueOf(ndef.getMaxSize()));

            Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);

            if (messages != null) {
                NdefMessage[] ndefMessages = new NdefMessage[messages.length];
                for (int i = 0; i < messages.length; i++) {
                    ndefMessages[i] = (NdefMessage) messages[i];
                }
            NdefRecord record = ndefMessages[0].getRecords()[0];

            byte[] payload = record.getPayload();
            int length = payload.length;

            new_payload = new byte[length-3];
            System.arraycopy(payload, 3, new_payload, 0,length-3);

            String text = new String(new_payload);

            txtRead.setText(text);
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();

            if(text.equalsIgnoreCase("silent")){
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
                AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_SILENT); 
            }
            if(text.equalsIgnoreCase("vibrate")){
                AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_VIBRATE); 
            }
            if(text.equalsIgnoreCase("normal")){
                AudioManager audiomanage = (AudioManager)getSystemService(Context.AUDIO_SERVICE);  
                audiomanage.setRingerMode(AudioManager.RINGER_MODE_NORMAL); 
            }

            ndef.close();

        }
        }
        catch (Exception e) {
            Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_LONG).show();
        }
    }   
} 

解决方案

The problem is, onNewIntent isnt called in onCreate method. The quick solutions that come to mind are:

in the onCreate method you could chceck the intent type. If its a tag being discover, you handle it just the same way as in onNewIntent.

Another solution would be to place the handling code in onResume (if tag reding is all your app does) and checking the intent there.

Maybe there are cleaner solutions, ill give it some thought later, but for now, this should help you.

这篇关于从NFC标签自动读取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆