简体   繁体   English

Android后台任务和生命周期

[英]Android background task and lifecycle

I'm currently working on an app that connects to a bluetooth device and receives a message every .25 seconds, then displays that data on screen. 我正在开发一个连接蓝牙设备的应用程序,每隔0.25秒接收一条消息,然后在屏幕上显示该数据。 The user will also be able to arbitrarily start/stop logging this data to a file on the SD card. 用户还可以任意开始/停止将此数据记录到SD卡上的文件中。

I have tried extending a thread class that listens for the messages from the BT device, and then using a handler to send the data back to the UI thread and display it. 我尝试扩展一个侦听来自BT设备的消息的线程类,然后使用处理程序将数据发送回UI线程并显示它。

This was working fine, but on configuration changes, like screen rotation, when the activity is destroyed and re-created the BT thread is duplicated and I can no longer communicate with it. 这工作正常,但在配置更改,如屏幕旋转,当活动被销毁和重新创建时,BT线程被复制,我不能再与它通信。 I have no problems, if I stop the BT thread in onStop() and re-start it in onResume() but then I need to re-connect to the BT device and if the user was logging data, that would be inturrupted. 我没有问题,如果我在onStop()中停止BT线程并在onResume()中重新启动它,但是我需要重新连接到BT设备,如果用户正在记录数据,那就会被破坏。

What is the correct way to accomplish this functionality? 完成此功能的正确方法是什么? Is there a way to setup my thread so it isn't duplicated or so I can re-connect to it after a config change? 有没有办法设置我的线程,所以它没有重复,所以我可以在配置更改后重新连接到它? Should I instead be looking at a service for my BT connection and logging, and then somehow get a feed from the service to display on the UI? 我是否应该为我的BT连接和日志记录查看服务,然后以某种方式从服务获取要在UI上显示的提要?

Thanks! 谢谢!

Should I instead be looking at a service for my BT connection and logging, and then somehow get a feed from the service to display on the UI? 我是否应该为我的BT连接和日志记录查看服务,然后以某种方式从服务获取要在UI上显示的提要?

Yes you should. 是的你应该。 I think this is a good approach. 我认为这是一个很好的方法。 You should run your thread the logs data in a service, and put the data that needs to be passed to the main UI or activity in a sharedpreference which will give ANY activity access to the information. 您应该在服务中运行线程日志数据,并将需要传递的数据放入共享首选项中的主UI或活动,这将为任何活动提供对信息的访问权限。

I think this would be the best way to go about doing this. 我认为这是实现这一目标的最佳方式。

OR 要么

You could use the method provided by alex.veprik 您可以使用alex.veprik提供的方法

You can prevent your activity from re-creating upon config changes. 您可以阻止您的活动在配置更改时重新创建。 Just modify the manifest file: 只需修改清单文件:

<activity android:name=".MyActivity"
          android:configChanges="keyboard|keyboardHidden|orientation" />

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

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