在我的应用程序中,我使用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);
}
发布于 2014-09-15 00:36:38
您不能禁用此行为。启动另一个应用程序是因为您的应用程序没有捕捉到标签。当您删除应用程序时,这将停止,但这当然不是解决方案。
如果你想防止这种情况,你应该在你的应用程序中捕获扫描到的标签,它在前台。
您已经知道如何使用enableForegroundDispatch
做到这一点。不要在扫描标签时禁用前台调度,而是创建一个标志或其他东西来确定是否要对标签执行某些操作。
例如:
doSomethingWithTheTag
doSomethingWithTheTag
应该为true
。如果是false
,不要对标记做任何事情。在大多数情况下,这将是您的onNewIntent
覆盖,只需确保每次活动覆盖您打开的对话框将doSomethingWithTheTag
设置为true
doSomethingWithTheTag
设置为true
希望我说清楚了。祝好运!
发布于 2016-05-11 19:46:35
我也遇到了同样的问题,在我的手机里安装了两个支持nfc的应用程序。每当我启动我的应用程序时,默认的应用程序就会打开,为此我创建了一个BaseActivity,并在我的所有活动中扩展它,在那里我覆盖了这两种方法
adapter.disableForegroundDispatch(mainActivity);
enableForegroundDispatch()
我有onNewIntent( intent )方法,只对感兴趣的活动感兴趣,我有一个检查,比如
@Override
protected void onNewIntent(Intent intent)
{
if (!isThisDialogWindow)
handleIntent(intent);
}
因此,当我的应用程序运行时,我摆脱了默认应用程序的打开。
笔记,但我仍然有一个问题,有时仍然打开其他应用程序时,我的应用程序运行。请天才来看看这个:-)
发布于 2019-07-28 09:00:11
我想我想出了一个简单的解决方案,那就是当你创建你的PendingIntent
时,对于第三个参数,简单地把new Intent()
。所以:
if (pendingIntent == null) {
pendingIntent = PendingIntent.getActivity(this, 0, new Intent(), 0);
}
然后将NFC适配器设置为:
adapter.enableForegroundDispatch(this, pendingIntent, null, null);
在所有的活动中,当你扫描NFC标签时,你不希望在你自己的应用程序中发生任何事情(尽管它会产生声音),你也不希望默认的Android NFC阅读器弹出。
https://stackoverflow.com/questions/25825188
复制相似问题