简体   繁体   中英

Keep connection alive?

In bluetooth chat example, I want to add another activity. When the connection is made and when the new activity is loaded, how do I still keep the connection alive??

After I load new activity, the onStop method is called and I canned send message using the connection made before. I tried the following code in my new activity:

    BluetoothChat bt = new BluetoothChat();        
    public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.special_keys);
    bt.sendMessage("hello");
    }

I manage to send the 'hello' but it force closes after that.. There must be an efficient way to handle this situation. Please help.

Thanks in advance.

I have recently created an Android application that communicates to a hardware device over Bluetooth. In my application, I have many Activity classes that communicate through the connection, and the application also performs continuous data logging from the connection in the background, too. Therefore, hopefully I might be able to help here. (This is my first attempt at posting an answer on StackOverflow, so go easy on me.)

In my application, I have first of all put all of the Bluetooth code into a separate dedicated class file (which I call BluetoothIF.java). The constructor in this class performs basic adapter initialization, and further methods are provided for tasks like making connections, etc. It contains the Runnable classes for establishing a connection and then transmitting / receiving over the established connection. (Essentially it is based upon the BluetoothChat example.)

I don't need to perform a massive amount of communication over the Bluetooth connection, and I also needed to have a Service in the background to continuously monitor and log data from the connection as previously mentioned. So, I instantiated my BluetoothIF within the Service. Any Activity classes that need to exchange data over the existing Bluetooth connection do so in my application by exchanging messages with the Service.

Alternatively, if you have no need for using a Service, perhaps you should share the Bluetooth object instance across Activitys using the singleton model or by extending the Application class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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