2014-09-13 170 views
2

在我的应用程序中,我使用NFC来读取标签。我点击按钮启用NFC。打开进度对话框以读取NFC标签,完成后NFC将被禁用。这一切工作正常。但是,当NFC未在应用程序中启用时,我将NFC标签放到手机上,默认的Android应用程序将读取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); 
} 
+0

你尝试调用'setupForegroundDispatch()'一旦你的应用程序运行? (例如在'onResume()'方法中) – mictter 2014-09-14 15:17:45

+0

[Android应用程序启用NFC仅适用于一个活动]的可能重复(http://stackoverflow.com/questions/24059027/android-app-enable-nfc-only-for-一个活动) – 2014-09-18 06:22:40

回答

3

您不能禁用此行为。另一个应用程序已启动,因为您的应用程序无法识别标签。当你删除应用程序,这将停止,但当然这不是解决方案。

如果你想防止这种情况发生,你应该抓住应用程序中的扫描标签,它位于前台。
您已经知道如何使用enableForegroundDispatch来做到这一点。扫描标签时不要禁用前台调度,但要创建一个标志或其他内容,以确定是否要对标签执行某些操作。

例如:

  • 创建一个属性例如doSomethingWithTheTag
  • 为您的标签处理程序添加一个条件,doSomethingWithTheTag应该是true。如果它是false请不要对标签做些什么。在大多数情况下,这将是您的覆盖,只要确保每个活动都会覆盖该功能。
  • 当你的对话框打开设置doSomethingWithTheTagtrue
  • 阅读标签,并处理它
  • 设置doSomethingWithTheTagfalse
  • 如果现在扫描标签,将您的应用逮住,但什么都不会发生。

希望我很清楚。祝你好运!

1

我遇到了同样的问题,在我的手机中安装了2个启用nfc的应用程序。每当我开始我的应用程序立即默认的应用程序打开,为了这个,我创建一个BaseActivity,它在我所有的活动扩展,并有我overrided两种方法

adapter.disableForegroundDispatch(mainActivity); 
enableForegroundDispatch() 

和我有onNewIntent(意向意图)方法只感兴趣的活动,我有一个支票像

@Override 
protected void onNewIntent(Intent intent) 
{ 
    if (!isThisDialogWindow) 
     handleIntent(intent); 
} 

所以我摆脱了默认应用程序,当我的应用程序运行时打开。

注意但我仍然有一个问题,有时仍然打开其他应用程序,当我的应用程序运行。请天才看看这个:-)