Android NFC mimeType被忽略,app始终在与标签或光束设备接触时启动

时间:2015-02-11 12:28:14

标签: java android nfc

我的应用有问题。它使用nfc标签进行某些操作(打开/锁定门)。 该应用在默认活动中有一个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。所以应用程序才刚刚开始,例如持有智能手机一起试图发送一些数据。如果我把索尼智能手表3拿到手机上,活动也会开始......

非常奇怪的是 - 如果我尝试使用这个简单的代码在一个新的应用程序上重现这个,那么应用程序不会在每个nfc命令上启动。

但在我的主应用程序中,没有更多nfc特定方法。

我完全迷失了。 有没有人知道如何跟踪/调试每个nfc数据打开应用程序的原因?

祝你好运, 尔根

2 个答案:

答案 0 :(得分:1)

在enableForegroundDispatch方法中,您必须添加过滤器和技术列表

例如:

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);

答案 1 :(得分:0)

看起来问题是enableForegroundDispatch。 我在onResume和onPause上注释了两个调用,并将Manifest更改为android:launchMode =&#34; singleTask&#34;它似乎工作。 必须是一些nfc bug,我不知道。

然而,在我的第一次测试中,它似乎现在正常工作,每次我在设备背面持有nfc标签时,应用程序都不会启动。