【问题标题】:NFC Android application is started twiceNFC Android 应用程序启动两次
【发布时间】:2017-09-29 23:24:50
【问题描述】:

我正在开发从 NFC 卡读取的应用程序。 问题如下: 用户通过点击应用程序图标启动应用程序。 应用准备扫描NFC卡,实现前台调度系统:

//Initialize Foreground NFC Dispatch System
mAdapter = NfcAdapter.getDefaultAdapter(this);
context=this;
mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, 
getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
try {
ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
                           You should specify only the ones that you need. 
*/
}
catch (IntentFilter.MalformedMimeTypeException e) {
throw new RuntimeException("fail", e);
}
mFilters = new IntentFilter[] { ndef, };
mTechLists = new String[][] { new String[] { MifareClassic.class.getName() } 
};

在清单中我有:

<activity
android:name="com.d_logic.cardcontrol.SplashScreenActivity"
android:screenOrientation="portrait">
<intent-filter>
    <action android:name="android.intent.action.MAIN"/>
    <category android:name="android.intent.category.LAUNCHER"/>
    <action android:name="android.nfc.action.TECH_DISCOVERED"/>
</intent-filter>
    <meta-data>
    <android:name="android.nfc.action.TECH_DISCOVERED">
    <android:resource="@xml/techlist"/>
</activity>

应用程序启动,然后用户按下主页按钮。 之后在后台运行应用程序,用户再次启动应用程序,但这次使用的是 NFC 卡。

此时我有两个相同应用程序的实例正在运行。

如何防止应用程序再次启动,但仍然可以使用 NFC 卡启动应用程序? 谢谢!

【问题讨论】:

    标签: android nfc


    【解决方案1】:

    避免使用这种逻辑两次:

    //put here in variable global 
    private long twiceCall;
    private static final int time_interval = 1500;
    
    // and put this to avoiding twice calling
    if (twiceCall + time_interval > System.currentTimeMillis()) {
            // If get the second time..
    } else {
            // Get the first time..
    }
    twiceCall = System.currentTimeMillis();
    

    【讨论】:

      【解决方案2】:

      利用

      android:launchMode:"standard/singleTop/singleTask/singleInstance"
      

      在manifest中保证同一个Activity的实例刚刚被带到前面并传递了新的Intent。您选择哪种模式取决于您的具体用例。

      “singleTop”或“singleTask”可能适用于您的 NFC 用例。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-30
        • 2015-02-27
        相关资源
        最近更新 更多