0

I am building a BTchat application project in android studio, The first activity sets up the connection and after the devices are connected we move to the next activity. I have used an application class with methods like getBTSocket() and setBTSocket(). In the second activity when there is the call of getBTSocket() my app closes/crashes(whatever you may call it).

Here is the code for socket.

public void setBluetoothSocket ( BluetoothSocket socket1 ) {
    socket = socket1;
}

public BluetoothSocket getBTSocket()  {
    return socket;
}

Please tell me what should I do.

1 Answers1

0

You can't do it without static field (bad way).

BluetoothSocket is not serializable and is not parcelable to send it through the Intent.

You need to open/close connection inside activity, and for navigation use only fragments. When activity calls onStop() - close connection, restart it onResume()

Another way is Android Service: https://developer.android.com/reference/android/app/Service

edwardstock
  • 168
  • 2
  • 10
  • how should I proceed with Service, I mean there is a serverThread(for listening) and a clientThread(for connecting to selected device) which I used in my code. How should I use service – Dev Saad Apr 28 '20 at 03:31