2011-02-26 61 views
1

我正在嘗試構建一個Android應用程序,我需要執行以下操作: 加載並等待,直到檢測到NFC標記。我並不在意標籤解析的方式(無論是智能海報還是URI等)。我唯一感興趣的是該標籤的ID。 一旦檢測到標籤及其ID,我想執行一些計算,然後返回到等待狀態(應用程序正在等待檢測NFC標籤的狀態)。帶NFC的Android應用程序

我的問題是,我無法弄清楚如何讓我的所有代碼被檢測到標籤觸發。 (請注意,應用程序正在運行,所以它不是應用程序優先級的問題,而是我希望通過檢測標記觸發我的代碼,然後返回到等待狀態)。

非常感謝您

+0

這裏工作示例:http://code.google.com/p/ndef-tools-for-安卓/ – ThomasRS 2012-11-26 21:39:25

回答

8

在這裏,我們走了,下面的代碼。訣竅是註冊前臺標籤分派,以便您的活動獲得所有新標籤。還要指定標誌SINGLE_TOP,以便使用onNewIntent調用活動的一個實例。也會發布ForegroundUtil。

public class DashboardActivity extends Activity { 

NFCForegroundUtil nfcForegroundUtil = null; 

private TextView info; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    info = (TextView)findViewById(R.id.info); 

    nfcForegroundUtil = new NFCForegroundUtil(this); 


} 

public void onPause() { 
    super.onPause(); 
    nfcForegroundUtil.disableForeground(); 
} 

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

    if (!nfcForegroundUtil.getNfc().isEnabled()) 
    { 
     Toast.makeText(getApplicationContext(), "Please activate NFC and press Back to return to the application!", Toast.LENGTH_LONG).show(); 
     startActivity(new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS)); 
    } 

} 

public void onNewIntent(Intent intent) { 
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); 
    info.setText(NFCUtil.printTagDetails(tag));  

} 


} 

前景的Util(您shoudl修改意圖過濾器,以滿足您的需求)

public class NFCForegroundUtil { 

private NfcAdapter nfc; 


private Activity activity; 
private IntentFilter intentFiltersArray[]; 
private PendingIntent intent; 
private String techListsArray[][]; 

public NFCForegroundUtil(Activity activity) { 
    super(); 
    this.activity = activity; 
    nfc = NfcAdapter.getDefaultAdapter(activity.getApplicationContext()); 

    intent = PendingIntent.getActivity(activity, 0, new Intent(activity, 
      activity.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0); 

    IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED); 

    try { 
     ndef.addDataType("*/*"); 
    } catch (MalformedMimeTypeException e) { 
     throw new RuntimeException("Unable to speciy */* Mime Type", e); 
    } 
    intentFiltersArray = new IntentFilter[] { ndef }; 

    techListsArray = new String[][] { new String[] { NfcA.class.getName() } }; 
    //techListsArray = new String[][] { new String[] { NfcA.class.getName(), NfcB.class.getName() }, new String[] {NfcV.class.getName()} }; 
} 

public void enableForeground() 
{ 
    Log.d("demo", "Foreground NFC dispatch enabled"); 
    nfc.enableForegroundDispatch(activity, intent, intentFiltersArray, techListsArray);  
} 

public void disableForeground() 
{ 
    Log.d("demo", "Foreground NFC dispatch disabled"); 
    nfc.disableForegroundDispatch(activity); 
} 

public NfcAdapter getNfc() { 
    return nfc; 
} 

} 
相關問題