SgtPepperAut
SgtPepperAut

Reputation: 133

How to run a method in specific intervals from a thread within a service...?

I am working with the Bluetooth chat example and I am trying to send "dummy" data in specific intervals from a thread that's active when the Bluetooth device is connected. Is it a good idea to start/stop another service to call a method in the original service every so often? How would I implement this?

private class ConnectedThread extends Thread {

    static private final String TAG = "PhoneInfoConnectedThread";
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket, String socketType) {
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
            Log.d(TAG, "In and out streams created");
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created " + e.getMessage());
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    // this is where we will spend out time when connected to the accessory.
    public void run() {
        // Keep listening to the InputStream while connected
        while (true) {
            // do whatever
        }
    }

    // Write to the connected OutStream.
    public void write(byte[] buffer) {
        if (mmOutStream == null) {
            Log.e(TAG, "ConnectedThread.write: no OutStream");
            return;
        }
        try {
            Log.d(TAG, "ConnectedThread.write: writing " + buffer.length
                    + " bytes");
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            // mHandler.obtainMessage(PhoneInfoActivity.MESSAGE_WRITE, -1,
            // -1, buffer).sendToTarget();
            Log.d(TAG, "ConnectedThread.write: sent to calling activity");
        } catch (IOException e) {
            Log.e(TAG, "Exception during write" + e.getMessage());
        }
    }

    public void cancel() {
        try {
            Log.d(TAG, "ConnectedThread.cancel: closing socket");
            if (mmSocket != null)
                mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "ConnectedThread.cancel: socket.close() failed"
                    + e.getMessage());
        }
    }
}

Upvotes: 1

Views: 198

Answers (1)

Jignesh Ansodariya
Jignesh Ansodariya

Reputation: 12705

May this example help you.

 MyTimerTask myTask = new MyTimerTask();
 Timer myTimer = new Timer();
 myTimer.schedule(myTask, 2000, 1000);


class MyTimerTask extends TimerTask {
  public void run() {
     Log.v("TAG","Message");
  }
}

for more information see this

Upvotes: 1

Related Questions