简体   繁体   English

点击另一个启用NFC的设备后,无法进入onNewIntent。(android)

[英]not getting to onNewIntent after tapping to another NFC enabled device.(android)

The main problem is that we are unable to go to onNewIntent() when i tap my phone with other NFC enabled phone(NFC is ON). 主要问题是,当我用其他启用了NFC的电话(NFC为ON)点击我的电话时,我们无法转到onNewIntent()。 Under no circumstances other than the main intent, i am unable to reach onNewIntent. 在主要意图之外的任何情况下,我都无法达到onNewIntent。 I have tried all the three filters NDEF,TECH, TAG. 我已经尝试了所有三个过滤器NDEF,TECH,TAG。

package com.example.nfctry;

import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.os.Bundle;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {
NfcAdapter adapter;
PendingIntent pendingIntent;
IntentFilter writeTagFilters[];
boolean writeMode;
Tag myTag;
Context ctx;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ctx = this;

    adapter = NfcAdapter.getDefaultAdapter(this);
    pendingIntent = PendingIntent.getActivity(this,0,new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);
    IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
    tagDetected.addCategory(Intent.CATEGORY_DEFAULT);
    writeTagFilters = new IntentFilter[] {tagDetected};

    onNewIntent(getIntent());



}

@Override
protected void onNewIntent(Intent intent)
{
    Toast.makeText(this,""+intent.getAction(), Toast.LENGTH_LONG).show();
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
    {
        myTag= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        Toast.makeText(this,"DETECTED muahhhhh"  + myTag.toString(), Toast.LENGTH_LONG).show();

    }


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

}

and in android mainfest i have added the intentfilters as well. 在android mainfest中,我也添加了intentfilters。

 <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.nfctry"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="15"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.nfctry.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
        <action android:name="android.nfc.action.NDEF_DISCOVERED" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.nfc.action.TECH_DISCOVERED" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.nfc.action.TAG_DISCOVERED" />

        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
        <meta-data
        android:name="android.nfc.action.TECH_DISCOVERED"
        android:resource="@xml/nfc_tech_filter" />
    </activity>
</application>

It's indepent off which TAG filter you use. 这与您使用哪个TAG过滤器无关。 Your onNewIntent only get's called when an intent is called using the launchMode : singleTop or singleTask and ofcourse when you call it yourself. onNewIntent只得到的当所谓的intent是使用所谓的launchModesingleTop或者singleTask和ofcourse当你自己调用它。 When your application is in the front it doesn't catch the NDEF/TECH/TAG discovery. 当您的应用程序位于最前面时,它不会捕获NDEF / TECH / TAG发现。 You need to use ForegroundDispatching to catch the tag discovery events in your current app. 您需要使用ForegroundDispatching来捕获当前应用程序中的标记发现事件。

When your ForegroundDispatch catch the event and you use PendingIntent.getActivity with the flag FLAG_ACTIVITY_SINGLE_TOP in your PendingIntent it will call onNewIntent . 当你的ForegroundDispatch赶上事件并使用PendingIntent.getActivityFLAG_ACTIVITY_SINGLE_TOP在你PendingIntent它会调用onNewIntent

You should enable the ForegroundDispatch in onResume : 您应该在onResume启用ForegroundDispatch

@Override
public void onResume()
{
    super.onResume();

    PendingIntent pendingIntent     = PendingIntent.getActivity(this,0,new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);     
    IntentFilter[] intentFilters    = { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };      

    adapter.enableForegroundDispatch(   this,
            pendingIntent, 
            intentFilters,
            new String[][]{
            new String[]{"android.nfc.tech.NfcA"}
        });     
}

And disable it in onPause : 并在onPause禁用它:

@Override
public void onPause() {
    super.onPause();

    if (adapter != null) 
    {
        try {
            adapter.disableForegroundDispatch(this);
        } 
        catch (NullPointerException e) {
        }
    }
}  

To catch the TAG event in your current code with ForegroundDispatch it will be something like this: 要使用ForegroundDispatch捕获当前代码中的TAG事件,将如下所示:

public class MainActivity extends Activity {

    NfcAdapter adapter;
    PendingIntent pendingIntent;
    IntentFilter writeTagFilters[];
    boolean writeMode;
    Tag myTag;
    Context ctx;    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ctx = this;
        adapter = NfcAdapter.getDefaultAdapter(this);
        onNewIntent(this.getIntent());      
    }


    @Override
    public void onNewIntent(Intent data) 
    {
        Toast.makeText(this,""+intent.getAction(), Toast.LENGTH_LONG).show();
        super.onNewIntent(intent);
        // getIntent() should always return the most recent
        if(NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()))
        {
            myTag= intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            Toast.makeText(this,"DETECTED muahhhhh"  + myTag.toString(), Toast.LENGTH_LONG).show();

        }
    }   

    @Override
    public void onResume()
    {
        super.onResume();

        PendingIntent pendingIntent     = PendingIntent.getActivity(this,0,new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),0);     
        IntentFilter[] intentFilters    = { new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED) };      

        adapter.enableForegroundDispatch(   this,
                pendingIntent, 
                intentFilters,
                new String[][]{
                new String[]{"android.nfc.tech.NfcA"}
            });     
    }

    @Override
    public void onPause() {
        super.onPause();

        if (adapter != null) 
        {
            try {
                adapter.disableForegroundDispatch(this);
            } 
            catch (NullPointerException e) {
            }
        }
    }    

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

Also note that you should add the NFC user permissions in your manifest. 还要注意,您应该在清单中添加NFC用户权限。

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

相关问题 NFC - OnNewIntent() 有时无法在 android 设备上运行 - NFC - OnNewIntent() sometime not working on android device MVP 中的 Android NFC 阅读器 - onNewIntent 未触发 - Android NFC Reader in MVP - onNewIntent not firing 错误“未在Android设备上安装应用程序。” - error “application not installed on android device.” 一段时间后检查是否仍启用NFC - Check after a period of time if NFC is still enabled 程序下载的文件无法在Android中打开。我重启Android设备后可以打开。 可能是什么问题? - Programatically downloaded file can not be opened in Android. It can be opened after I restart Android device. What may be the problem? 奇怪的问题-Android应用在某些设备上崩溃。 为什么? - weird issue - android app crashes at some of the device. why is it? 是否可以从Android设备发送HDMI CEC命令。 - Is it possible to send HDMI CEC commands from an Android Device. 在Android设备上运行时,FontMetrics不正确。模拟器很好 - FontMetrics not correct when run on android device. Simulator fine Android 附近的连接无法连接到设备。 总是返回 8011 - Android Nearby Connections cannot connect to device. Always returns 8011 接收中的异常:java.net.SocketException:没有此类设备。 在android组播中 - Exception in recieving: java.net.SocketException: No such device. in android multicast
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM