마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

특정 값 이상이면 소리 울리기

0 추천

글자 색을 변경하려다가 실패하고 ㅜㅜ .. 소리를 울리는 방법으로 변경해서 해보려고 합니다..

private class ConnectedBluetoothThread extends Thread {
        private final BluetoothSocket mmSocket;
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;
 
        public ConnectedBluetoothThread(BluetoothSocket socket) {
            mmSocket = socket;
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
 
            try {
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "소켓 연결 중 오류가 발생했습니다.", Toast.LENGTH_LONG).show();
            }
 
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }
        public void run() {
            byte[] buffer = new byte[1024];
            int bytes;
 
            while (true) {
                try {
                    bytes = mmInStream.available();
                    if (bytes != 0) {
                        SystemClock.sleep(100);
                        bytes = mmInStream.available();
                        bytes = mmInStream.read(buffer, 0, bytes);
                        mBluetoothHandler.obtainMessage(BT_MESSAGE_READ, bytes, -1, buffer).sendToTarget();
                    }
                    if (byte >= 1200) {
                        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                        Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), notification);
                        ringtone.play();
                     }
                } catch (IOException e) {
                    break;
                }
            }
        }
        public void write(String str) {
            byte[] bytes = str.getBytes();
            try {
                mmOutStream.write(bytes);
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "데이터 전송 중 오류가 발생했습니다.", Toast.LENGTH_LONG).show();
            }
        }
        public void cancel() {
            try {
                mmSocket.close();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(), "소켓 해제 중 오류가 발생했습니다.", Toast.LENGTH_LONG).show();
            }
        }
    }
}

if (byte >=1200) 조건을 안쓰면 소리가 계속 나긴 합니다..

아두이노 블루투스로 연결해서 센서값을 받아와서, 센서 값이 1200 이상이 되면 알림음을 울리게 하고 싶습니다 ㅜㅜ

어느부분을 수정하면 되는지 힌트 주시면 감사하겠습니다 ㅠㅠ

 

황제 (230 포인트) 님이 2022년 6월 3일 질문
혹시 byte가 아니고 bytes아닌가요?
그리고
mBluetoothHandler.obtainMessage(BT_MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 부분에서 이미 데이터를 뷰에 보내고 있는데, 데이터를 받을 때마다 보내는 이유는 뭔가요?
bytes 맞습니다 코드를 올리면서 수정했더니 byte로 작성했네요
데이터를 받고 계속 화면에 띄우기 위해서 데이터를 받을 때 마다 보냈습니다 ,,

2개의 답변

0 추천

올리신 코드를 기반으로 코드를 정리해 봤습니다.

public class BluetoothActivity extends AppCompatActivity implements ConnectedBluetoothThread.Listener {

    private ConnectedBluetoothThread bluetoothThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bluetooth);

        startBluetooth();
    }

    private void startBluetooth() {
        BluetoothSocket bluetoothSocket = ...
        bluetoothThread = new ConnectedBluetoothThread(bluetoothSocket);
    }

    @Override
    protected void onStart() {
        super.onStart();
        bluetoothThread.setListener(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        bluetoothThread.setListener(null);
    }

    @Override
    public void onSensorThresholdReached() {
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Ringtone ringtone = RingtoneManager.getRingtone(BluetoothActivity.this, notification);
        ringtone.play();
    }

    @Override
    public void onSensorDataReceiveError() {

    }

    @Override
    public void onSensorConnectionError() {
        showToastOnUiThread("소켓 연결 중 오류가 발생했습니다.");
    }

    @Override
    public void onSensorWriteError() {
        showToastOnUiThread("데이터 전송 중 오류가 발생했습니다.");
    }

    @Override
    public void onSensorCancelError() {
        showToastOnUiThread("소켓 해제 중 오류가 발생했습니다.");
    }

    private void showToastOnUiThread(String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                shortToast(message);
            }
        });
    }
    
    private void shortToast(String message) {
        Toast.makeText(BluetoothActivity.this, message, Toast.LENGTH_LONG).show();
    }
}

 

class ConnectedBluetoothThread extends Thread {

    interface Listener {
        void onSensorThresholdReached();
        void onSensorDataReceiveError();
        void onSensorConnectionError();
        void onSensorWriteError();
        void onSensorCancelError();
    }

    private static final int SENSOR_THRESHOLD = 1200;

    private static final Object BT_MESSAGE_READ = new Object();

    private Listener listener;
    private final BluetoothSocket mSocket;
    private final InputStream mInStream;
    private final OutputStream mOutStream;

    public ConnectedBluetoothThread(BluetoothSocket socket) {
        mSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            if (listener != null) listener.onSensorConnectionError();
        }

        mInStream = tmpIn;
        mOutStream = tmpOut;
    }

    public void setListener(Listener listener) {
        this.listener = listener;
    }

    public void run() {
        byte[] buffer = new byte[1024];
        int bytesReceived;

        while (true) {
            try {
                bytesReceived = mInStream.available();
                if (bytesReceived != 0) {
                    SystemClock.sleep(100);
                    bytesReceived = mInStream.available();
                    bytesReceived = mInStream.read(buffer, 0, bytesReceived);
                    // 아래라인이 어떤 역할을 하는지 정확하지 않아서 주석처리함.
                    //mBluetoothHandler.obtainMessage(BT_MESSAGE_READ, bytes, -1, buffer).sendToTarget(); 
                }

                if (bytesReceived >= SENSOR_THRESHOLD && listener != null) {
                    listener.onSensorThresholdReached();
                }

            } catch (IOException e) {
                if (listener != null) listener.onSensorDataReceiveError();
            }
        }
    }

    public void write(String str) {
        byte[] bytes = str.getBytes();
        try {
            mOutStream.write(bytes);
        } catch (IOException e) {
            if (listener != null) listener.onSensorWriteError();
        }
    }

    public void cancel() {
        try {
            mSocket.close();
        } catch (IOException e) {
            if (listener != null) listener.onSensorCancelError();
        }
    }
}

 

spark (226,420 포인트) 님이 2022년 6월 3일 답변
spark님이 2022년 6월 3일 수정
리스너 오류가 납니다 ㅠㅠ
0 추천

질문에 작성한 코드 위쪽입니다.

첨부한 코드 위쪽으로는 import

첨부한 코드 하단에는 질문에 작성한 코드가 붙습니다

한꺼번에 전부 다 는 첨부가 안되네요

public class MainActivity extends AppCompatActivity {
    TextView mTvBluetoothStatus;
    TextView mTvReceiveData;
    TextView mTvSendData;
    Button mBtnBluetoothOn;
    Button mBtnBluetoothOff;
    Button mBtnConnect;
    Button mBtnSendData;

    BluetoothAdapter mBluetoothAdapter;
    Set<BluetoothDevice> mPairedDevices;
    List<String> mListPairedDevices;

    Handler mBluetoothHandler;
    ConnectedBluetoothThread mThreadConnectedBluetooth;
    BluetoothDevice mBluetoothDevice;
    BluetoothSocket mBluetoothSocket;

    final static int BT_REQUEST_ENABLE = 1;
    final static int BT_MESSAGE_READ = 2;
    final static int BT_CONNECTING_STATUS = 3;
    final static UUID BT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTvBluetoothStatus = (TextView)findViewById(R.id.tvBluetoothStatus);
        mTvReceiveData = (TextView)findViewById(R.id.tvReceiveData);
        mTvSendData =  (EditText) findViewById(R.id.tvSendData);
        mBtnBluetoothOn = (Button)findViewById(R.id.btnBluetoothOn);
        mBtnBluetoothOff = (Button)findViewById(R.id.btnBluetoothOff);
        mBtnConnect = (Button)findViewById(R.id.btnConnect);
        mBtnSendData = (Button)findViewById(R.id.btnSendData);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();


        mBtnBluetoothOn.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothOn();
            }
        });
        mBtnBluetoothOff.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                bluetoothOff();
            }
        });
        mBtnConnect.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                listPairedDevices();
            }
        });
        mBtnSendData.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(mThreadConnectedBluetooth != null) {
                    mThreadConnectedBluetooth.write(mTvSendData.getText().toString());
                    mTvSendData.setText("");
                }
            }
        });
        mBluetoothHandler = new Handler(){
            public void handleMessage(android.os.Message msg){
                if(msg.what == BT_MESSAGE_READ){
                    String readMessage = null;
                    try {
                        readMessage = new String((byte[]) msg.obj, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    mTvReceiveData.setText(readMessage);
                }
            }
        };
    }
    void bluetoothOn() {
        if(mBluetoothAdapter == null) {
            Toast.makeText(getApplicationContext(), "블루투스를 지원하지 않는 기기입니다.", Toast.LENGTH_LONG).show();
        }
        else {
            if (mBluetoothAdapter.isEnabled()) {
                Toast.makeText(getApplicationContext(), "블루투스가 이미 활성화 되어 있습니다.", Toast.LENGTH_LONG).show();
                mTvBluetoothStatus.setText("활성화");
            }
            else {
                Toast.makeText(getApplicationContext(), "블루투스가 활성화 되어 있지 않습니다.", Toast.LENGTH_LONG).show();
                Intent intentBluetoothEnable = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(intentBluetoothEnable, BT_REQUEST_ENABLE);
            }
        }
    }
    void bluetoothOff() {
        if (mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.disable();
            Toast.makeText(getApplicationContext(), "블루투스가 비활성화 되었습니다.", Toast.LENGTH_SHORT).show();
            mTvBluetoothStatus.setText("비활성화");
        }
        else {
            Toast.makeText(getApplicationContext(), "블루투스가 이미 비활성화 되어 있습니다.", Toast.LENGTH_SHORT).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case BT_REQUEST_ENABLE:
                if (resultCode == RESULT_OK) { // 블루투스 활성화를 확인을 클릭하였다면
                    Toast.makeText(getApplicationContext(), "블루투스 활성화", Toast.LENGTH_LONG).show();
                    mTvBluetoothStatus.setText("활성화");
                } else if (resultCode == RESULT_CANCELED) { // 블루투스 활성화를 취소를 클릭하였다면
                    Toast.makeText(getApplicationContext(), "취소", Toast.LENGTH_LONG).show();
                    mTvBluetoothStatus.setText("비활성화");
                }
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    void listPairedDevices() {
        if (mBluetoothAdapter.isEnabled()) {
            mPairedDevices = mBluetoothAdapter.getBondedDevices();

            if (mPairedDevices.size() > 0) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("장치 선택");

                mListPairedDevices = new ArrayList<String>();
                for (BluetoothDevice device : mPairedDevices) {
                    mListPairedDevices.add(device.getName());
                    //mListPairedDevices.add(device.getName() + "\n" + device.getAddress());
                }
                final CharSequence[] items = mListPairedDevices.toArray(new CharSequence[mListPairedDevices.size()]);
                mListPairedDevices.toArray(new CharSequence[mListPairedDevices.size()]);

                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int item) {
                        connectSelectedDevice(items[item].toString());
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();
            } else {
                Toast.makeText(getApplicationContext(), "페어링된 장치가 없습니다.", Toast.LENGTH_LONG).show();
            }
        }
        else {
            Toast.makeText(getApplicationContext(), "블루투스가 비활성화 되어 있습니다.", Toast.LENGTH_SHORT).show();
        }
    }
    void connectSelectedDevice(String selectedDeviceName) {
        for(BluetoothDevice tempDevice : mPairedDevices) {
            if (selectedDeviceName.equals(tempDevice.getName())) {
                mBluetoothDevice = tempDevice;
                break;
            }
        }
        try {
            mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(BT_UUID);
            mBluetoothSocket.connect();
            mThreadConnectedBluetooth = new ConnectedBluetoothThread(mBluetoothSocket);
            mThreadConnectedBluetooth.start();
            mBluetoothHandler.obtainMessage(BT_CONNECTING_STATUS, 1, -1).sendToTarget();
        } catch (IOException e) {
            Toast.makeText(getApplicationContext(), "블루투스 연결 중 오류가 발생했습니다.", Toast.LENGTH_LONG).show();
        }
    }
황제 (230 포인트) 님이 2022년 6월 6일 답변
황제님이 2022년 6월 7일 수정
...