简体   繁体   English

如何将字符串从活动发送到主活动[ANDROID]中调用的线程

[英]How to send string from an activity to a thread called in main activity [ANDROID]

I'm developing a bluetooth chat for android. 我正在为Android开发蓝牙聊天。 This is the problem: 这就是问题:

My main activity A starts a thread to manage bt connection, and then A starts a new activity B. I must know a way to send String continually from the activity B to the thread called in main activity A. How can I do it? 我的主要活动A启动一个线程来管理bt连接,然后A启动一个新的活动B。我必须知道一种将String从活动B连续发送到主活动A中调用的线程的方法。我该怎么做?

If you directly start a thread, then there is no way of accessing that thread from another activity and may cause memory leaks. 如果直接启动线程,则无法从其他活动访问该线程,并且可能导致内存泄漏。

Your best option is to have separate Service to manage Bluetooth connection. 最好的选择是拥有单独的Service来管理蓝牙连接。

You can have a separate Service and initiate the tread form the Service ( Service runs in the main thread). 你可以有一个单独的Service和启动tread形成ServiceService运行在主线程)。

And You have to be careful with the starting and stopping of the Service . 并且您在启动和停止Service必须小心。

There are 2 ways to start the Service , 2种方式来启动Service

You can start a Service or you can bind to a S strong text ervice. 您可以启动 Service ,也可以绑定到S 强文本服务。

In your case you will have to start the service in can bind to the service form both Activity A and Activity B, or you can start the service in Activity A and bind to it from Activity B. 在您的情况下,您将必须启动服务才能绑定到活动A和活动B的服务,或者您可以在活动A中启动服务并从活动B绑定到该服务。

But only thing you will have to be careful is when to stop the service. 但是,您唯一需要注意的是何时停止服务。 otherwise you will have memory leaks. 否则您将发生内存泄漏。

Once the service is up and running you can communicate with it from-to your Activity. 服务启动并运行后,您就可以与它之间的活动进行通信。 and you can pass what ever information to the tread running in the Service component. 您可以将任何信息传递给在Service组件中运行的踏板。

You can read on this in processes-and-threads and services 您可以在processes-and-threads以及services对此进行阅读

You can do it via Bind and Callback interface. 您可以通过“绑定和回调”界面进行操作。 Please refer old thread. 请参考旧线程。

Communication between Activity and Service 活动与服务之间的沟通

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

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