我正在开发的应用程序应该收到一个光束,然后从 onResume 调用 processIntent(intent) 函数。我遇到的问题是,当它接收到光束时,它会打开一个全新的应用程序实例,而不是仅仅停留在活动中(我已经调用了 enableForegroundDispatch)。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null){
Toast.makeText(this, "No NFC on this device", Toast.LENGTH_LONG).show();
}
// Create a PendingIntent object so the Android system can populate it with the details of the tag when it is scanned.
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
// Declare intent filters to handle the intents that the developer wants to intercept.
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("application/com.sample.mime/string");
} catch (MalformedMimeTypeException e) {
Log.wtf("mimeexception", e);
e.printStackTrace();
}
intentFiltersArray = new IntentFilter[] {ndef};
... ...
}
public void onResume() {
super.onResume();
// Enable the foreground dispatch when the Activity regains focus.
NfcAdapter.getDefaultAdapter(this).enableForegroundDispatch(this, pendingIntent, intentFiltersArray, null);
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
public void onPause() {
super.onPause();
// Disable the foreground dispatch when the Activity loses focus.
NfcAdapter.getDefaultAdapter(this).disableForegroundDispatch(this);
}
void processIntent(Intent intent){
// do stuff
}
这是清单中的活动
<activity
android:name="com.example.app.opensthisonebutshouldnt"
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="com.example.app.shouldopenthisone"
android:label="@string/title_activity_create_invoice"
android:launchMode="singleTop" >
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />\
<category android:name="android.intent.category.DEFAULT" />\
<data android:mimeType="application/com.example.nfctest/invoice" />
</intent-filter>
</activity>
感谢您的输入