我正在
android项目中实现NFC.我编写了
AndroidManifest.xml和Java代码中所需的条目.
当任何标签靠近设备然后我的应用程序检测到标签然后它打开活动但在这里我得到NFC标签信息但是onNewIntent没有执行.
请各位分享您的观点.
public class NFCActivity extends Activity { private NfcAdapter mNFCAdapter; private PendingIntent mNfcPendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_nfc); // Create the OpensqliteHelper object. It always best to create only // once instance of this OpensqliteHelper DatabaseManager.init(this); mNFCAdapter = NfcAdapter.getDefaultAdapter(this); if (mNFCAdapter == null) { // Device does not support NFC Toast.makeText(this,getString(R.string.device_does_not_support_nfc),Toast.LENGTH_LONG).show(); } else { if (!mNFCAdapter.isEnabled()) { // NFC is disabled Toast.makeText(this,getString(R.string.enable_nfc),Toast.LENGTH_LONG).show(); } else { mNfcPendingIntent = PendingIntent.getActivity(NFCActivity.this,new Intent(NFCActivity.this,NFCActivity.class) .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0); } } finish(); } @Override protected void onNewIntent(Intent intent) { Tag mTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG); } @Override protected void onPause() { super.onPause(); mNFCAdapter.disableForegroundDispatch(this); } @Override public void onResume() { super.onResume(); mNFCAdapter.enableForegroundDispatch(this,mNfcPendingIntent,null,null); } }
AndroidManifest.xml中
<activity android:name="net.livepatrols.thepartnerSA.NFCActivity" android:theme="@android:style/Theme.NoDisplay" > <intent-filter> <action android:name="android.nfc.action.TECH_DISCOVERED" /> </intent-filter> <Meta-data android:name="android.nfc.action.TECH_DISCOVERED" android:resource="@xml/nfc_tech_filter" /> <intent-filter> <action android:name="android.nfc.action.TAG_DISCOVERED" /> <category android:name="android.intent.category.DEFAULT" /> </intent-filter> </activity>
解决方法
从我看到你的活动不是启动器,所以我知道你想在发现标签时启动你的活动.如果您的活动位于前台,则代码可以正常工作,但如果Activity由android.nfc.action.XXX_DISCOVERED的Intent启动,则不会调用onNewIntent().您应该在另一个方法上执行nfc逻辑并将其命名为onCreate()和onNewIntent().
public class NFCActivity extends Activity { private NfcAdapter mNFCAdapter; private PendingIntent mNfcPendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ... performTagOperations(getIntent()); } @Override protected void onNewIntent(Intent intent) { performTagOperations(intent); } private void performTagOperations(Intent intent){ String action = intent.getAction(); if(action.equals(NfcAdapter.ACTION_TAG_DISCOVERED) || action.equals(NfcAdapter.ACTION_TECH_DISCOVERED) ){ PERFORM TAG OPERATIONS } } ... }