Android的后台任务和生命周期 [英] Android background task and lifecycle

查看:237
本文介绍了Android的后台任务和生命周期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在对连接到蓝牙设备,并收到一条消息,每隔0.25秒的应用程序,然后显示在屏幕上的数据。用户还可以随意启动/停止该数据记录到SD卡上的文件。

我试图扩大它侦听来自英国电信设备的消息一个线程类,然后使用一个处理程序将数据发送回UI线程并显示。

这是工作的罚款,但在配置更改,如屏幕旋转,当活动被破坏并重新创建的线程BT是重复的,我可以用它不再沟通。我没有问题,在onResume如果我停止的onStop(BT的线程),并重新启动它(),但是我需要重新连接到BT设备,如果用户被记录数据,这将inturrupted。

什么是实现该功能的正确方法是什么?有没有办法设置我的线程,这样它就不会重复或这样我就可以一个配置变化后重新连接到它?我应该不是在看我的BT连接和日志记录服务,然后以某种方式从服务中获得的原料,以显示在UI?

谢谢!


解决方案

  

我应该不是在看一个服务,为我的BT连接和记录,然后以某种方式从服务中获得的原料,以显示在UI?


是的,你应该。我觉得这是一个不错的办法。你应该在一个服务运行的线程在日志数据,并把需要传递给在共享preference主UI或活动,这将给该信息的任何活动访问的数据。

我认为这将是去这样做的最佳方式。

您可以使用由alex.veprik提供的方法

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. The user will also be able to arbitrarily start/stop logging this data to a file on the SD card.

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.

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. 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.

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?

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?

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.

I think this would be the best way to go about doing this.

OR

You could use the method provided by alex.veprik

这篇关于Android的后台任务和生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆