来吧,下面的代码。诀窍是注册前台标签调度,以便您的活动获得所有新标签。还要指定标志 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));
}
}
Foreground-Util(你应该修改意图过滤器以满足你的需要)
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;
}
}