我的应用程序有问题。它使用 nfc 标签进行某些操作(开/锁门)。 该应用在默认 Activity 中有一个 intent-filter:
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/de.juwei.myapplication" />
</intent-filter>
但它似乎完全忽略了 mimeType 设置,因为即使我将一个空标签附加到手机上,并且如果我尝试从另一部手机传输数据,它也会启动。
代码只是这样做:
public class MainActivity extends ActionBarActivity {
private NfcAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = NfcAdapter.getDefaultAdapter(this);
Intent intent = getIntent();
// see if app was started from a tag
if (mAdapter != null && intent.getType() != null && intent.getType().equals("application/de.juwei.myapplication")) {
}
}
@Override
protected void onResume() {
super.onResume();
if (mAdapter != null) {
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
mAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
@Override
protected void onPause() {
super.onPause();
if (mAdapter != null) {
mAdapter.disableForegroundDispatch(this);
}
}
@Override
public void onNewIntent(Intent intent) {
if (mAdapter != null && intent.getType() != null && intent.getType().equals("application/de.juwei.myapplication")) {
// ... reading tag
}
}
}
如果标签没有我的 mimetype,则 getIntent() 为 null。因此,如果将智能手机放在一起尝试传输一些数据,则该应用程序才刚刚启动。如果我将索尼智能 watch 3 放在手机上, Activity 也会开始......
非常奇怪的是——如果我试图用那个简单的代码在一个新的应用程序上重现这个,应用程序不会在每个 nfc 命令上启动。
但在我的主应用程序中,没有更多的 nfc 特定方法。
我完全迷路了。 有谁知道如何通过每条 nfc 数据跟踪/调试应用打开的原因?
最好的问候, 于尔根
最佳答案
在 enableForegroundDispatch 方法中你必须添加过滤器和 techLists
例如:
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
try {
ndef.addDataType("*/*"); /* Handles all MIME based dispatches.
You should specify only the ones that you need. */
}
catch (MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] {
ndef,
};
mTechLists = new String[][] { new String[] { NfcF.class.getName() } };
NfcAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
mTechLists);
关于java - Android NFC mimeType 被忽略,应用程序始终在与标签或光束设备接触时启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28454356/