I have created an application that does the following steps very well -
Connects with the Remote Device (
SPP
) using Bluetooth socket .Then listens for the stream coming from the remote bluetooth device in a separate thread.
Then when data stream comes, it passes the data stream to the handler to parse it.
When data is parsed, a broadcast is sent and the records are created into the database.
Now I want to add a new functionality -
When the application is in the back ground and is "connected" to remote device, it needs to continue to process the data stream and create records.
So once I get the socket connected, I am passing the result "connected" to the onPostExecute()
method.
IMPORTANT NOTE:
1) My all socket related work ( socket connection, socket data parse, data handler ) is in the fragment.
2) Once the connection is established, the private class (Thread - ConnectedThread.java) in the fragment is keep listening to the InputStream
public class EntryFragment extends Fragment{
//More fragment code here then this
public class ConnectedThread extends Thread {
public ConnectedThread(BluetoothSocket socket) {
//code initialization stuff
}
public void run() {
// Keep listening to the InputStream until an exception occurs
while (true)
{
// Read from the InputStream
if(mmInStream.available() > 0)
{
bytes = mmInStream.read(buffer);
mHandler.obtainMessage(MESSAGE_READ,
bytes, -1, buffer).sendToTarget();
}
}
}
}
3) My handler that handles the Read of step 2
case MESSAGE_READ:
//Call to AsyncTask to do background processing of data
new parseStream(getActivity()).execute();
break;
4) I am connected so do something from onPostExecute() of AsyncTask parseStream
@Override
protected void onPostExecute(Void result) {
//Database related work here
//Result is connected so listen to data if app goes to background after this state
if(result.equals("connected"))
{
Log.i(TAG, "CONNECTED TO Remote Device!");
Toast.makeText(getActivity(),"CONNECTED TO Remote
Device!",Toast.LENGTH_SHORT).show();
//Do something when connected
setSetting("STATUS", "Connected");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();
//Do I need to call Service here to handle data ?????
Intent serviceIntent= new Intent(context, DataProcessService.class);
getActivity().startService(serviceIntent);
}
}
5) I called service in step 4 with the intention that it will execute when app will go background
and process data. But then how will it communicate with the Fragment because my whole work of
data processing is in the fragment. Do I really need it to process data OR should I call
broadcast receiver here as it can also process in the background ?