5

インテント android.nfc.action.TAG_DISCOVERED が送信されたときに呼び出されるアプリを作ったのですが、その後 onNewIntent メソッドでカードの情報を取得したいのですが、この種の処理方法がわかりません。 nfc カード。次のコードで試しました:

    public void onNewIntent(Intent intent) {
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        //do something with tagFromIntent
        NfcA nfca = NfcA.get(tagFromIntent);
        try{
            nfca.connect();
            Short s = nfca.getSak();
            byte[] a = nfca.getAtqa();
            String atqa = new String(a, Charset.forName("US-ASCII"));
            tv.setText("SAK = "+s+"\nATQA = "+atqa);
            nfca.close();
        }
        catch(Exception e){
            Log.e(TAG, "Error when reading tag");
            tv.setText("Error");
        }
    }

tv は TextView ですが、このコードを実行しても変更されません。

4

2 に答える 2

2

OnNewIntentは、アクティビティがすでに実行されており、singleTaskに設定されている場合に呼び出されます。コードを独自のメソッドにして、onCreate()とonNewIntent()で呼び出す必要があります。

于 2012-12-16T20:09:50.437 に答える
1

上位レベル (NDEF_DISCOVERED または TECH_DISCOVERED) で同じタグを管理できる他のアプリがある場合、下位レベルのみを管理するアプリは呼び出されません。

アプリを使用するには、タグをスキャンするよりも、アプリを開く必要があります。

アプリが起動しない場合は、次の手順を完了していることを確認してください。

OnCreate() で NfcAdapter を取得します。

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

   ....
   mNfcAdapter = NfcAdapter.getDefaultAdapter(this);

   if (mNfcAdapter == null) {
      // Stop here, we definitely need NFC
      Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
      finish();
      return;
    }

    //method to handle your intent
    handleTag(getIntent());
}

onResume で、フォアグラウンド ディスパッチを有効にします。

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

   final Intent intent = new Intent(this.getApplicationContext(), this.getClass());
   final PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, 0);

    mNfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}

onPause で無効にします。

@Override
protected void onPause() {
   mNfcAdapter.disableForegroundDispatch(this);

   super.onPause();
}

onNewIntent で、関数を呼び出してインテントを処理します

@Override
protected void onNewIntent(Intent intent) {
   super.onNewIntent(intent);

   handleTag(intent);
}

関数でタグを処理します。

private void handleTag(Intent intent){
   String action = intent.getAction();
   Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);

   if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action){

      // here your code
   }
}

マニフェストにアクセス許可を追加することを忘れないでください。

<uses-permission android:name="android.permission.NFC" />

<uses-feature  
   android:name="android.hardware.nfc"
   android:required="true" />

<activity>
   ....
   <intent-filter>
      <action android:name="android.nfc.action.TAG_DISCOVERED"/>
   </intent-filter>
</activity>

詳細はこちらNFC BasisおよびこちらNFCタグを読む

于 2014-09-18T03:45:01.770 に答える