1

我曾经DeepLink在检测到这样的某个 url 地址后启动我的应用程序NFC

        <activity
            android:name=".view.main.MainActivity"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.nfc.action.NDEF_DISCOVERED" />
                <action android:name="android.nfc.action.TECH_DISCOVERED" />
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <category android:name="android.intent.category.DEFAULT" />

                <data
                    android:host="example.com"
                    android:scheme="http" />
            </intent-filter>

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

但是,即使我已经启动了我的应用程序,它也可以工作。因此,重复的活动不断出现。有时,它会导致我的应用出现故障或崩溃。我只想Deeplink在不使用我的应用程序时使用。

有没有办法解决这个问题?

4

2 回答 2

2

您可以使用launchMode="singleTop". 这样,如果 Activity 已经启动并且位于堆栈的顶部,则任何新的启动都将通过此实例进行路由,您将在onNewIntent()方法中将其作为回调。

<activity android:name=".view.main.MainActivity" 
          android:launchMode="singleTop" />
于 2019-06-12T05:29:13.080 回答
1

Dinesh 的解决方案似乎应该可行,但如果它给您带来问题,您可以尝试另一种(更复杂)的解决方案。您可以使用该NfcAdapter.enableForegroundDispatch()方法来控制android.nfc.action.TECH_DISCOVEREDActivity 中的操作并确保它不执行任何操作。

您可以通过将以下两种方法添加到您的MainActivity(或将代码添加到现有方法中)来实现:

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

    //create a broadcast intent that doesn't trigger anything
    Intent localIntent = new Intent("fake.action");
    localIntent.setPackage(getApplicationContext().getPackageName());
    localIntent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);

    //set the NFC adapter to trigger our broadcast intent
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.enableForegroundDispatch(
            this,
            PendingIntent.getBroadcast(this, 0, localIntent, PendingIntent.FLAG_UPDATE_CURRENT),
            new IntentFilter[] {new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED)},
            new String[][] { { "android.nfc.tech.IsoDep" /* add other tag types as necessary */ } });

}

@Override
protected void onPause() {
    super.onPause();
    NfcAdapter nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcAdapter.disableForegroundDispatch(this);
}

现在,只要您的活动可见并且检测到 NFC 标签,就不会触发任何操作。(或者,更具体地说,它会触发一个没有注册方法的广播。)

希望这可以帮助。

于 2019-06-12T14:17:13.447 回答