1

我正在尝试读取 NFC 标签 ID。我知道我无法读取数据,因为它是一个安全标签(MBTA 票价卡)。我想读取标签的唯一 ID 并敬酒该值。我已成功使 NFC 意图工作,因此当扫描标签时,我的应用程序会尝试处理它。但是,应用程序不会显示带有标签 ID 的吐司。

    package com.example.nfctest;

import android.nfc.NdefMessage;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcF;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.util.Log;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {
     private NfcAdapter mAdapter;
        private PendingIntent mPendingIntent;
        private IntentFilter[] mFilters;
        private String[][] mTechLists;
        private int mCount = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mAdapter = NfcAdapter.getDefaultAdapter(this);

        // Create a generic PendingIntent that will be deliver to this activity. The NFC stack
        // will fill in the intent with the details of the discovered tag before delivering to
        // this activity.
        mPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Setup an intent filter for all MIME based dispatches



    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
    try {
        ndef.addDataType("*/*");
    } catch (MalformedMimeTypeException e) {
        throw new RuntimeException("fail", e);
    }
    mFilters = new IntentFilter[] {

    };

    // Setup a tech list for all NfcF tags
    mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
}
public void onResume() {
    super.onResume();
    mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);

}

@Override
public void onNewIntent(Intent intent) {
    Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
    CharSequence text = ("Discovered tag " + ++mCount + " with intent: " + intent);
    int duration = Toast.LENGTH_SHORT;

    Tag myTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);


    Toast toast = Toast.makeText(MainActivity.this,myTag.getId().toString() , duration);
    toast.show();
}


@Override
public void onPause() {
    super.onPause();
    //mAdapter.disableForegroundDispatch(this);
    throw new RuntimeException("onPause not implemented to fix build");
}



@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

它不再崩溃,只是不使用 ID 敬酒。

4

1 回答 1

0

我强烈推荐这个链接中的这个示例应用程序。不要像我一样尝试一切来成功简单的操作,从而给自己带来痛苦。

您可能在 onResume 和 onNewIntent 中的操作位置上做错了。但是,在我链接的示例中,它在 onResume 和 onNewIntent 中都有新标签和 ndef 控件。如果你真的想继续自己的项目,试试这个。

于 2013-01-15T02:01:07.323 回答