简体   繁体   English

如何在独立应用程序中保存有关wear os android 的数据

[英]How to save data on wear os android in standalone app

Hi on android apps I used onSaveInstanceState to persist my data when I rotate the phone or exit app.嗨,在 Android 应用程序上,当我旋转手机或退出应用程序时,我使用 onSaveInstanceState 来保存我的数据。 Now I'm making Wear Os for smartwatch app that will be stand-alone but will be also able to connect to my app on the phone.现在我正在为智能手表应用程序制作 Wear Os,该应用程序将是独立的,但也可以连接到我的手机应用程序。 So I manage to connect a phone and wear app with DataClient but my problem is when I start the app on the watch, get some score and then exit the app by swiping from left to right my app my score is reset to zero.因此,我设法将手机与 DataClient 连接并佩戴应用程序,但我的问题是当我在手表上启动应用程序,获得一些分数,然后通过从左向右滑动我的应用程序退出应用程序时,我的分数被重置为零。 Interesting is that the score is saved if I exit the app with the power button but I don't think that has to do anything with my onSaveInstanceState.有趣的是,如果我使用电源按钮退出应用程序,分数会被保存,但我认为这与我的 onSaveInstanceState 无关。

I tried to use onSaveInstanceState in wear app but it does not work.我尝试在 Wear 应用程序中使用 onSaveInstanceState 但它不起作用。 When I tried to debug it is not called.当我尝试调试时,它没有被调用。 I guess it is not supported to work on wear and that I have to, somehow, use DataClient API for this but I don't know how to use it for this purpose.我想不支持在磨损上工作,我必须以某种方式为此使用 DataClient API,但我不知道如何为此目的使用它。 This is all new to me and I'm still a beginner.这对我来说是全新的,我仍然是初学者。 I only manage to send images from a phone app to wear app but I want to be able to save data without phone connected and to retrieve it.我只设法从手机应用程序发送图像以佩戴应用程序,但我希望能够在没有连接手机的情况下保存数据并检索它。

I just want to save data from my UI so when a user comes back to my app that data is not lost.我只想从我的 UI 保存数据,这样当用户回到我的应用程序时,数据不会丢失。 So need some simple sample code like saving some int or string and retrieving it when the app is started again.所以需要一些简单的示例代码,比如保存一些 int 或 string 并在应用程序再次启动时检索它。

I decided that for me the best is to use Kotlin Room.我决定对我来说最好的是使用 Kotlin Room。 I needed to save my data anyway in database so this way I just save it every time the data is changed.我无论如何都需要将我的数据保存在数据库中,这样我每次更改数据时都会保存它。 Maybe more efficient would be to save it just in onPause or onStop but I don't have a lot of data so this works for me.也许更有效的方法是将它保存在 onPause 或 onStop 中,但我没有很多数据,所以这对我有用。

You can use standard Android storage APIs to store data locally, as you would on a phone.您可以使用标准的 Android 存储 API 在本地存储数据,就像在手机上一样。 For example, you can use the SharedPreferences APIs or the Room persistence library.例如,您可以使用 SharedPreferences API 或 Room 持久性库。 https://developer.android.com/training/wearables/apps/standalone-apps#shared-code https://developer.android.com/training/wearables/apps/standalone-apps#shared-code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM