简体   繁体   English

如何在Android应用程序中全局读取NFC标签数据

[英]How to read NFC tag data globally inside an Android Application

I would like to read the NFC tag data inside my application. 我想在我的应用程序中读取NFC标签数据。 Basically I have different NFC tags associated with different actions to perform inside my application. 基本上,我有与要在我的应用程序中执行的不同操作相关的不同NFC标签。 I know declaring the IntentFilter inside the Service is a bad idea. 我知道在Service内部声明IntentFilter是一个坏主意。 I don't want to associate this to any Activity . 我不想将此与任何Activity相关联。

Here is my manifest: 这是我的清单:

 <service android:name="com.yo.helpers.NFCReaderHelper"
        android:enabled="true"
        android:exported="true" >
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:scheme="http" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.nfc.action.NDEF_DISCOVERED" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
 </service>

Here is my Service class: 这是我的服务班级:

@Override
protected void onHandleIntent(Intent intent) {
    Log.d("yoyo", "Service");
    Tag mTag = null;
    if(intent.getAction()!=null)
    {
        if(intent.getAction().equals("android.nfc.action.NDEF_DISCOVERED"))
            Log.d("yoyo", "Intent call");

        mTag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Log.i("tag ID", bytesToHexString(mTag.getId()));            
    }
}

I don't get the call inside the onHandleIntent method. 我没有在onHandleIntent方法中得到调用。 If I do the same inside an Activity then I receive the intent inside the onNewIntent method. 如果我在Activity执行相同的操作,那么我会在onNewIntent方法中收到该意图。

You can't receive the NFC discovery intents ( NDEF_DISCOVERED , TECH_DISCOVERED , TAG_DISCOVERED ) with a service (or a broadcast receiver). 您无法通过服务(或广播接收器)接收NFC发现意图( NDEF_DISCOVEREDTECH_DISCOVEREDTAG_DISCOVERED )。 NFC on Android is designed as a means of user interaction and, hence, these intents are only delivered to activities. Android上的NFC被设计为用户交互的一种方式,因此,这些意图仅传递给活动。

A trick that you could use is to use an invisible/transparent activity to handle the intent. 您可以使用的技巧是使用不可见/透明活动来处理意图。 See How to run android program without open the app? 请参阅如何在不打开应用程序的情况下运行android程序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM