2013-12-23 68 views
0

我在我的主要活動中有此代碼。在此活動中,我將數據寫入NFC標籤。完美這項工作:應該工作,但不工作這個NFC代碼

public class MainActivity extends Activity implements OnClickListener { 
private NfcAdapter mAdapter; 
private boolean mInWriteMode; 
private Button mWriteTagButton; 
private TextView mTextView; 

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

    // grab our NFC Adapter 
    mAdapter = NfcAdapter.getDefaultAdapter(this); 

    // button that starts the tag-write procedure 
    mWriteTagButton = (Button)findViewById(R.id.write_tag_button); 
    mWriteTagButton.setOnClickListener(this); 

    // TextView that we'll use to output messages to screen 
    mTextView = (TextView)findViewById(R.id.text_view); 
} 

public void onClick(View v) { 
    if(v.getId() == R.id.write_tag_button) { 
     displayMessage("Touch and hold tag against phone to write."); 
     enableWriteMode(); 
    } 
} 

@Override 
protected void onPause() { 
    super.onPause(); 
    disableWriteMode(); 
} 

/** 
* Called when our blank tag is scanned executing the PendingIntent 
*/ 
@Override 
public void onNewIntent(Intent intent) { 
    if(mInWriteMode) { 
     mInWriteMode = false; 

     // write to newly scanned tag 
     Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
     writeTag(tag); 
    } 
} 

/** 
* Force this Activity to get NFC events first 
*/ 
private void enableWriteMode() { 
    mInWriteMode = true; 

    // set up a PendingIntent to open the app when a tag is scanned 
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, 
     new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED); 
    IntentFilter[] filters = new IntentFilter[] { tagDetected }; 

    mAdapter.enableForegroundDispatch(this, pendingIntent, filters, null); 
} 

private void disableWriteMode() { 
    mAdapter.disableForegroundDispatch(this); 
} 

/** 
* Format a tag and write our NDEF message 
*/ 
private boolean writeTag(Tag tag) { 
    // record to launch Play Store if app is not installed 
    NdefRecord appRecord = NdefRecord.createApplicationRecord(getPackageName()); 

    // record that contains our custom "retro console" game data, using custom MIME_TYPE 
    byte[] payload = getRandomConsole().getBytes(); 
    byte[] mimeBytes = MimeType.NFC_DEMO.getBytes(Charset.forName("US-ASCII")); 
    NdefRecord cardRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, mimeBytes, 
              new byte[0], payload); 
    NdefMessage message = new NdefMessage(new NdefRecord[] { cardRecord, appRecord}); 

    try { 
     // see if tag is already NDEF formatted 
     Ndef ndef = Ndef.get(tag); 
     if (ndef != null) { 
      ndef.connect(); 

      if (!ndef.isWritable()) { 
       displayMessage("Read-only tag."); 
       return false; 
      } 

      // work out how much space we need for the data 
      int size = message.toByteArray().length; 
      if (ndef.getMaxSize() < size) { 
       displayMessage("Tag doesn't have enough free space."); 
       return false; 
      } 

      ndef.writeNdefMessage(message); 
      displayMessage("Tag written successfully."); 
      return true; 
     } else { 
      // attempt to format tag 
      NdefFormatable format = NdefFormatable.get(tag); 
      if (format != null) { 
       try { 
        format.connect(); 
        format.format(message); 
        displayMessage("Tag written successfully!\nClose this app and scan tag."); 
        return true; 
       } catch (IOException e) { 
        displayMessage("Unable to format tag to NDEF."); 
        return false; 
       } 
      } else { 
       displayMessage("Tag doesn't appear to support NDEF format."); 
       return false; 
      } 
     } 
    } catch (Exception e) { 
     displayMessage("Failed to write tag"); 
    } 

    return false; 
} 

private String getRandomConsole() { 
    double rnd = Math.random(); 
    if(rnd<0.25) return "Random-1"; 
    else if(rnd<0.5) return "Random-2"; 
    else if(rnd<0.75) return "Random-3"; 
    else return "Random-4"; 
} 

private void displayMessage(String message) { 
    mTextView.setText(message); 
} 

}

然後,這是我讀NFC標籤德數據的活動。理論上,當發現NFC標籤時,這是系統啓動但系統啓動之前活動的活動。這是代碼:

public class CardActivity extends Activity { 
private TextView mCardView; 

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

    // ImageView that we'll use to display cards 
    mCardView = (TextView)findViewById(R.id.card_view); 

    // see if app was started from a tag and show game console 
    Intent intent = getIntent(); 
    if(intent.getType() != null && intent.getType().equals(MimeType.NFC_DEMO)) { 
     Parcelable[] rawMsgs = getIntent().getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
     NdefMessage msg = (NdefMessage) rawMsgs[0]; 
     NdefRecord cardRecord = msg.getRecords()[0]; 
     String consoleName = new String(cardRecord.getPayload()); 
     mCardView.setText(consoleName); 
    } 
} 

}

清單文件是這樣的:

<?xml version="1.0" encoding="utf-8"?> 

<uses-sdk android:minSdkVersion="14" android:targetSdkVersion="19" /> 

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

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 
      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <activity 
     android:name=".CardActivity" 
     android:label="@string/app_name" > 

     <intent-filter> 
      <action android:name="android.nfc.action.NDEF_DISCOVERED"/> 
      <data android:mimeType="application/vnd.daggothSoft.nfcdemo"/> 
      <category android:name="android.intent.category.DEFAULT"/> 
     </intent-filter> 
    </activity> 

</application> 

並與MIME類型的最後一項活動是:

public class MimeType { 
public static final String NFC_DEMO = "application/vnd.daggothSoft.nfcdemo"; 

}

的問題是,當我掃描NFC標籤,即啓動該系統的活動是不是應該根據清單。始終啓動主要活動。我不知道問題出在哪裏,問題是什麼,以及.....好的,任何意見或幫助都將非常有用。

謝謝你,真的,謝謝;)

回答

0

關注的是,對於意圖過濾器,Android的MIME類型匹配是區分大小寫的 - eventhough的MIME類型本身不是。因此,對於Android(並且幾乎在任何地方都使用它們),您應該遵守約定,只使用小寫字母的MIME類型。

具體來說,在NFC標籤上存儲MIME類型記錄時,Android會自動將它們轉換爲全小寫字母,以解決意圖過濾器中區分大小寫的問題。因此,在你的榜樣,在意向更換過濾器的類型名稱"application/vnd.daggothsoft.nfcdemo"將工作:

<intent-filter> 
    <action android:name="android.nfc.action.NDEF_DISCOVERED"/> 
    <data android:mimeType="application/vnd.daggothsoft.nfcdemo"/> 
    <category android:name="android.intent.category.DEFAULT"/> 
</intent-filter> 

然後,你還應該確保你只有小寫字母寫的MIME類型:

public static final String NFC_DEMO = "application/vnd.daggothsoft.nfcdemo"; 
相關問題