2014-11-04 70 views
1

我想我的ActivityNFCSender通過NFC發送一個整數到我的ActivityNFCReceiver。下面的代碼工作。但是有一個問題:當連接建立時,兩個活動顯示提示發送!但我只希望第一個能夠發送(一個整數)並顯示提示。怎麼做?Android NFC:一個活動發送和一個只接收

ActivityNFCSender

public class ActivityNFCSender extends ActivityBase { 

public static final String EXTRA_RES_ID = "res_id"; 

private NfcAdapter mNfcAdapter; 
private int mReservServerId; 


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

    mReservServerId = getIntent().getIntExtra(EXTRA_RES_ID, 0); 
} 


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

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    if(mNfcAdapter == null){ 
     messageDialogQuit(R.string.error_no_nfc); 
    } 
    else if(!mNfcAdapter.isEnabled()){ 
     new AlertDialog.Builder(this).setCancelable(true).setMessage(R.string.error_nfc_off) 
      .setPositiveButton(R.string.turn_on, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.dismiss(); 
         Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS); 
         startActivity(settingsIntent);       
        } 
       }) 
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.dismiss();  
         finish(); 
        } 
       })     
      .create().show(); 
    } 
    else{   
     //Set sending 
     mNfcAdapter.enableForegroundNdefPush(ActivityNFCSender.this, getIntAsNdef(mReservServerId)); 
    } 
} 

public void onPause(){  
    if(mNfcAdapter != null && mNfcAdapter.isEnabled()){ 
     mNfcAdapter.disableForegroundNdefPush(this); 
    } 
    super.onPause();   
} 


private NdefMessage getIntAsNdef(int pInt) { 
    byte[] textBytes = (pInt+"").getBytes(Charset.forName("UTF8")); 
    NdefRecord textRecord = new NdefRecord(NdefRecord.TNF_MIME_MEDIA, "text/plain".getBytes(), new byte[] {}, textBytes); 
    return new NdefMessage(new NdefRecord[] { 
     textRecord 
    }); 
} 

ActivityNFCReceiver

public class ActivityNFCReceiver extends ActivityBase { 

private NfcAdapter mNfcAdapter; 
private PendingIntent mNfcPendingIntent; 
private IntentFilter[] mNdefExchangeFilters;  


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

    ((TextView) findViewById(R.id.nfcTVStatus)).setText(R.string.receiving); 
} 


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

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    if(mNfcAdapter == null){ 
     messageDialogQuit(R.string.error_no_nfc); 
    } 
    else if(!mNfcAdapter.isEnabled()){ 
     new AlertDialog.Builder(this).setCancelable(true).setMessage(R.string.error_nfc_off) 
      .setPositiveButton(R.string.turn_on, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.dismiss(); 
         Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS); 
         startActivity(settingsIntent);       
        } 
       }) 
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { 
        public void onClick(DialogInterface dialog, int id) { 
         dialog.dismiss();  
         finish(); 
        } 
       })     
      .create().show(); 
    } 
    else{   
     mNfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 
     // Intent filters for exchanging over p2p. 
     IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); 
     try { 
      ndefDetected.addDataType("text/plain"); 
     } 
     catch (MalformedMimeTypeException e) { 
      e.printStackTrace(); 
     } 

     mNdefExchangeFilters = new IntentFilter[] { ndefDetected }; 

     //set receiving 
     mNfcAdapter.enableForegroundDispatch(ActivityNFCReceiver.this, mNfcPendingIntent, mNdefExchangeFilters, null); 
    } 
} 

public void onPause(){  
    if(mNfcAdapter != null && mNfcAdapter.isEnabled()){ 
     mNfcAdapter.disableForegroundDispatch(ActivityNFCReceiver.this); 
    } 
    super.onPause();   
} 


@Override 
protected void onNewIntent(Intent intent) { 
    if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) { 
     NdefMessage[] msgs = getNdefMessages(intent); 
     if(msgs.length > 0){ 
      try{ 
       NdefRecord firstRecord = msgs[0].getRecords()[0]; 
       byte[] payload = firstRecord.getPayload(); 
       String str = new String(payload, Charset.forName("UTF8")); 

       int reservServerId = Integer.parseInt(str); 
       returnResult(reservServerId); 
      } 
      catch(Exception e){ 
       messageDialog(R.string.error_during_NFC); 
      } 
     } 
    } 
} 


public void onCancelClicked(View pV){ 
    finish(); 
} 

private NdefMessage[] getNdefMessages(Intent intent) { 
    // Parse the intent 
    NdefMessage[] msgs = null; 
    String action = intent.getAction(); 
    if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action) || NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) { 
     Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES); 
     if (rawMsgs != null) { 
      msgs = new NdefMessage[rawMsgs.length]; 
      for (int i = 0; i < rawMsgs.length; i++) { 
       msgs[i] = (NdefMessage) rawMsgs[i]; 
      } 
     } 
     else { 
      // Unknown tag type 
      byte[] empty = new byte[] {}; 
      NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, empty, empty); 
      NdefMessage msg = new NdefMessage(new NdefRecord[] { record }); 
      msgs = new NdefMessage[] { msg }; 
     } 
    } 
    else { 
     Log.d(TAG, "Unknown intent."); 
     finish(); 
    } 
    return msgs; 
} 


private void returnResult(int pResServerId){ 
    Intent result = new Intent(); 
    result.putExtra(ActivityCompanySubMenu.EXTRA_RES_SERVER_ID, pResServerId); 
    setResult(RESULT_OK, result); 
    finish(); 
} 

}

回答

1

您可以(即你的ActivityNFCReceiver)使用NfcAdapter.setNdefPushMessage禁用梁UI特定活動方法:

public void onCreate(Bundle savedInstanceState) { 

    [...] 

    mNfcAdapter = NfcAdapter.getDefaultAdapter(this); 
    if (mNfcAdapter != null) { 
     mNfcAdapter.setNdefPushMessage(null, this); 
    } 
} 

請注意,enableForegroundNdefPush方法已經由於Android 4.0(API等級14),並且非常支持NFC使用Android 4.0或更高版本的所有Android設備過時。


雖然禁用梁UI這種方式適用於Nexus設備,並正式記錄的路要走(見setNdefPushMessage):

如果setNdefPushMessage(...)被調用空NDEF消息,則對於指定的活動,NDEF推送將被完全禁用。這也會禁用Android操作系統爲了這些活動而以其他名義發送的任何默認NDEF消息。

看來,不幸的是,這不適用於某些Android設備的NFC實施。例如,它在運行Android 4.3的三星Galaxy S3上不起作用。

+0

我改變了代碼並添加了mNfcAdapter.setNdefPushMessage(null,this);就在mNfcAdapter.enableForegroundDispatch之後(ActivityNFCReceiver.this,mNfcPendingIntent,mNdefExchangeFilters,null);在接收器活動中,但結果相同:兩臺設備都將提示顯示給SEND。我可能是錯的,但我認爲enableForegroundDispatch()函數是啓用RECEIVING。我希望接收器活動處於前景並接收整數。 – Yar 2014-11-05 08:22:59

+0

順便說一下,ANY活動顯示了這個系統提示(活動圖像變小了,Android問我是否要發送,什麼?我不知道)。感謝您的迴應,希望您能進一步幫助我... – Yar 2014-11-05 08:47:09

+0

一般來說,您應該儘早在活動life-cylce中使用setNdefPushMessage(即在'onCreate()')中。但是,這並不能解釋爲什麼Beam UI會顯示在您的案例中。你使用的是哪種Anadroid版本? – 2014-11-05 09:09:40

相關問題