2
votes

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();
        }
    }   
} 
1
Note that you can check the intent directly for NDEF messages, no need to connect/close. Like so in this boilerplate project.ThomasRS
I tried that to but its not working.....I have to scan the tag two times..ssg

1 Answers

1
votes

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.