1

私は Bluetooth チャットの例で作業しており、Bluetooth デバイスが接続されているときにアクティブなスレッドから特定の間隔で「ダミー」データを送信しようとしています。別のサービスを開始/停止して、元のサービスのメソッドを頻繁に呼び出すことは良い考えですか? これをどのように実装しますか?

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());
        }
    }
}
4

1 に答える 1

1

この例が役に立ちますように。

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


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

詳細については、これを参照してください

于 2013-03-05T04:46:28.493 に答える