自动从NFC标签读取数据

时间:2012-09-24 09:37:07

标签: android nfc

您好我正在尝试从NFC标签中读取数据。阅读Tha数据没有问题。但我必须扫描我的标签两次才能显示数据。我第一次扫描标签时会启动应用程序,但不会读取数据。因此,要读取数据,我必须再次扫描我的标签。那么我该怎么办呢,一旦我扫描我的标签,它应该启动应用程序以及从标签读取数据。该应用程序是从标签读取数据并更改我的Android手机的配置文件。这是我的代码.. 谢谢....

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();
        }
    }   
} 

1 个答案:

答案 0 :(得分:1)

问题是,在onCreate方法中没有调用onNewIntent。想到的快速解决方案是:

在onCreate方法中,您可以选择意图类型。如果它的标签被发现,你就像处理onNewIntent一样处理它。

另一个解决方案是将处理代码放在onResume中(如果标签reding是你的所有应用程序都做的)并检查那里的意图。

也许有更清洁的解决方案,以后会考虑一下,但是现在,这应该对你有帮助。