如何在android studio 中安全地处理资源?

How to dispose of resources safely in android studio?

就像在 visual studio WinForms 中一样。在退出应用程序之前,我首先关闭所有连接。否则,应用程序仍将 运行 在后台运行。我通过单击表单本身然后单击 closeBeforeexiting 属性.

来执行此操作

然后我在应用程序退出之前关闭所有连接。

我的问题是,如何在 android 工作室中执行此操作?我想在退出应用程序之前先关闭 RFID class。原因是设备上的另一个应用程序使用相同的 RFID class。但由于 RFID class 没有安全关闭并且仍在后台 运行ning,其他应用程序崩溃,因为它无法访问此 class.

android studio 中是否有 closeBeforeexit 属性,也许在 res->layout->content_main.xml 中,它为我提供了与 visual studio 中相同的功能

我可以使用应用程序上的退出按钮来执行此操作,但我看到人们通常使用屏幕上已有的后退按钮退出应用程序。有什么方法可以访问此后退按钮并将我的关闭连接功能放在那里吗?

答案:

@Override
public void onBackPressed()
{
    try {
        RFIDReader reader = RFID.open();
        reader.stop();
        reader.close();
        super.onBackPressed();
        return;
    }
    catch (ReaderException e) {
        Toast.makeText(this, "Error: " + e, Toast.LENGTH_LONG).show();
    }
}

是的,你可以拦截后退按钮并在那里做任何你想做的事情(甚至取消后退导航),但是你会错过用户通过主页按钮离开的情况,或者来电,或者通过通知...

您应该做的是为您的 activity 覆盖 onPauseonStop、and/or、onDestroy 方法。它们都是与 activity 生命周期相关的回调,您很快就会需要了解它。

简而言之:onPause 发生在您失去焦点时,onStop 发生在您不再可见时,onDestroy 发生在 activity 被完全删除(例如用户按下“后退”,但通常不会在他们按下“主页”时按下)。

在你的情况下,onStop可能是最合适的。

My question is then, how do I do this in an android studio? I want to close of a RFID class first before exiting the app. The reason for this is another app on the device that uses the same RFID class. But since the RFID class did not close safely and is still running in the background, the other application crashes because it cannot access this class.

您最好阅读 -> Understand the Activity Lifecycle 以了解 Android 如何处理活动和后台任务。如果你是 运行 后台任务中的任务,你应该可以使用 close() 方法关闭 RFID。

I could do this using an exit button on the application but I see people generally use the back button that is already on the screen to exit the application. Is there any way I can access this back button and put my close conection funstion in there?

使用 onBackPressed() method should help in your case. Keep in mind that finish() 方法不是关闭 Activity 的好方法。

Is there a closeBeforeexit property in android studio, perhaps in the res->layout->content_main.xml that provides me with the same functionality as in visual studio

layout->content_main.xml 是 Android 中的 UI 布局,为了能够处理这些事情,您需要使用 java 或 Kotlin。