对多个活动使用 USB-Intent 过滤器

Using USB-Intent filter for multiple activities

我目前有两项活动。一个是登录 activity,成功登录后会导致包含多个片段的主 activity。

我目前有一个 USB intent 过滤器和广播接收器,用于检查是否插入了 USB 设备。一旦它检测到它是一个设备并且我将其设置为该设备的默认应用程序,它甚至会重新启动该应用程序如果我目前在主activity。问题是它绕过了登录屏幕 activity 并崩溃,因为它不包含第二个 activity 的数据,因为没有发生登录。

我的问题发生在应用程序重新启动和重置连接这一事实上。有没有办法让应用程序不重新启动或只重新加载第二个 activity 中的最后一个片段?

<application 
        android:theme="@style/AppTheme"
        android:allowBackup="true"
        android:name=".MainApplication" 
        android:icon="@drawable/icon" 
        android:label="@string/app_name">

        <activity  
                android:name=".LoginActivity"
                android:theme="@style/Theme.Dark">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
        </activity>                   

        <activity   
                android:name=".DeviceRegistrationActivity"
                android:theme="@style/Theme.Dark"/>

        <activity   
                android:name=".navDrawer"
                android:theme="@style/Theme.Dark">
                <intent-filter>
                    <category android:name="android.intent.category.DEFAULT" />
                    <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                </intent-filter>

                <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
                    android:resource="@xml/device_filter" />

The problem is that it bypasses the log in screen activity and crashes as it does not contain the data for the 2nd activity as no log in has occured.

那么您不应该将登录过程放在一个单独的 activity 中。让登录过程成为一个片段,由与 USB 事件启动的片段相同的 activity 显示。如果 activity 启动时,它确定它没有身份验证信息——无论出于何种原因——它会显示登录片段。

Is there a way I can make the app not relaunch

不是真的。 Android 设备没有无限 RAM。您的进程 最终终止,并且您在静态数据成员或其他单例中缓存的任何内容(例如身份验证数据)都将消失。

or just reload the last fragment within the 2nd activity?

当然欢迎您让第 2 届 activity 展示您想要的任何内容。但是,如果您没有身份验证数据,"whatever you want it to" 最好是获取该数据的片段。