在我的应用程序中使用NFC时如何禁用默认的Android NFC应用程序

max*_*xxo 2 java android nfc

在我的应用中,我正在使用NFC读取标签。我单击按钮以启用NFC。将打开一个进度对话框以读取NFC标记,完成后将禁用NFC。一切都很好。但是,当应用程序中未启用NFC且我在手机上放置了NFC标签时,默认的Android应用程序会读取NFC标签并将我的应用程序置于后台。

如何禁用Android应用程序?

我的启用/禁用NFC的代码:

/**
 * @param activity The corresponding {@link Activity} requesting the foreground dispatch.
 * @param adapter  The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][]{};

    // Notice that this is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    try {
        filters[0].addDataType(MIME_TEXT_PLAIN);
    } catch (IntentFilter.MalformedMimeTypeException e) {
        throw new RuntimeException(activity.getString(R.string.exception_wrong_mime_type));
    }

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}

/**
 * @param activity The corresponding {@link MainActivity} requesting to stop the foreground dispatch.
 * @param adapter  The {@link NfcAdapter} used for the foreground dispatch.
 */
public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
    adapter.disableForegroundDispatch(activity);
}
Run Code Online (Sandbox Code Playgroud)

S.P*_*ols 5

您不能禁用此行为。因为您的应用程序没有捕获到标签,所以启动了另一个应用程序。当您删除该应用程序时,该操作将停止,但这当然不是解决方案。

如果要防止这种情况,则应在前台应用程序中捕获扫描的标签。
您已经知道如何使用enableForegroundDispatch。扫描标签时不要禁用前台调度,而要创建一个标志或确定您是否要对标签执行操作的操作。

例如:

  • 创建一个属性,例如 doSomethingWithTheTag
  • 添加一个条件,你的标记处理程序doSomethingWithTheTag应该是true。如果false不是,请对标签执行任何操作。在大多数情况下,这将是您的onNewIntent替代,只需确保每个活动都覆盖该功能即可。
  • 对话框打开时,将设置doSomethingWithTheTagtrue
  • 阅读标签并处理
  • 设置doSomethingWithTheTagfalse
  • 如果您现在扫描标签,则该标签将被您的应用程序捕获,但是什么也不会发生。

希望我明白。祝好运!