Как отправить данные из службы bluetooth на андроид, используя различные действия в arduino - PullRequest
0 голосов
/ 12 октября 2018

Я пытаюсь отправить данные на Arduino через службу Bluetoth, которая запускается в действии, но данные, которые я хочу отправить, обрабатываются в другом действии, так как я пытаюсь отправить некоторые данные с того места, где я запустил службуно у меня не было никакого успеха.Я не знаю, как вызвать метод записи из моего сервиса. Соединение установлено правильно, что не похоже на отправку данных

Мой сервис запускается из действия.

private  AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        String info = ((TextView) view).getText().toString();
        final String address = info.substring(info.length() - 17);
        final String name = info.substring(0,info.length() - 17);
        if(!address.equals(mBTaddress)){
            Intent intentBTService = new Intent(BluetoothActivity.this,BluetoothService_Test.class);
            intentBTService.putExtra("device_address",address);
            startService(intentBTService);
        }else{
            Toast.makeText(getBaseContext(), "Dispositivo Conectado", Toast.LENGTH_SHORT).show();
        }


    }
};

Это мой сервис.

public class BluetoothService_Test extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    msg.obj = intent;
    mServiceHandler.sendMessage(msg);
    return START_NOT_STICKY;
}



 private CountHandler mServiceHandler;

private final class CountHandler extends Handler{
    CountHandler(Looper looper){
        super(looper);
    }
    @Override
    public void handleMessage(Message msg){
        Intent request = (Intent) msg.obj;
        String address = request.getStringExtra("device_address");
        int starId =msg.arg1;
        if (address != null){
            mBluetoothAdapter =BluetoothAdapter.getDefaultAdapter();
            mBTDevice = mBluetoothAdapter.getRemoteDevice(address);
            connect(mBTDevice);

        }

    }
}



@Override
public void onCreate() {
    super.onCreate();
    HandlerThread backgroundThread  = new HandlerThread("CounterThread",
            Process.THREAD_PRIORITY_BACKGROUND);
    backgroundThread .start();
    mServiceHandler =  new CountHandler(backgroundThread.getLooper());
    localBroadcastManager = LocalBroadcastManager.getInstance(getApplicationContext());
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onDestroy() {
    stop();
}

и это функции, которые я использую

public synchronized void connect(BluetoothDevice device) {
    // Cancel any thread attempting to make a connection
    if (mState == S_STATE_CONNECTING) {
        if (mConnectThread != null) {
            mConnectThread.cancel();
            mConnectThread = null;
        }
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }
    // Start the thread to connect with the given device
    mConnectThread = new ConnectThread(device);
    mConnectThread.start();
}

private class ConnectThread extends Thread {
    private BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {

        this.mmDevice = device;
        BluetoothSocket tmp = null;
        try {
            tmp = mmDevice.createRfcommSocketToServiceRecord(mBTUUID);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //mmSocket = tmp;
        mBTSocket = tmp;
        mState = S_STATE_CONNECTING;
        Intent resultIntent = new Intent(ACTION_BT_SERVICE_CONNECTING);
        localBroadcastManager.sendBroadcast(resultIntent);

    }

    @Override
    public void run() {
        boolean connected = false;
        mBluetoothAdapter.cancelDiscovery();
        try {
            mBTSocket.connect();
            //mmSocket.connect();
            connected = true;
        } catch(IOException e) {
            try {
                mBTSocket.connect()
                connected = false;
            } catch(IOException close) {
                connected = false;
            }
        }
        if(connected){
            synchronized (BluetoothService_Test.this) {
                mConnectThread = null;
            }
            // Reset the ConnectThread because we're done
            connected(mBTSocket); //Next step in the connection
        }else{
            connectionFailed();
            return;
        }
    }
    public void cancel() {
        try {
            mBTSocket.close();
            //mBTSocket = null;

        } catch (IOException e) {

        }
    }

}

 public synchronized void connected(BluetoothSocket socket) {
    // Cancel the thread that completed the connection
    if (mConnectThread != null) {
        mConnectThread.cancel();
        mConnectThread = null;
    }
    // Cancel any thread currently running a connection
    if (mConnectedThread != null) {
        mConnectedThread.cancel();
        mConnectedThread = null;
    }
    // Start the thread to manage the connection and perform transmissions
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();
}

это моя функция ConnectedThread

private class ConnectedThread extends Thread{
   // private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket){

        mBTSocket = socket;
        //mmSocket = socket;
        InputStream tempIn = null;
        OutputStream temOut = null;

        try {
            tempIn = mBTSocket.getInputStream();
            temOut = mBTSocket.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        mmInStream = tempIn;
        mmOutStream = temOut;
        mState = S_STATE_CONNECTED;


        mState = S_STATE_CONNECTED;
        String nameDevice = mBTDevice.getName();
        String nameAddress = mBTDevice.getAddress();
        Intent resultIntent = new Intent(ACTION_BT_SERVICE_CONNECTED);
        resultIntent.putExtra("addressDevice",nameAddress);
        resultIntent.putExtra("nameDevice",nameDevice);
        localBroadcastManager.sendBroadcast(resultIntent);
    }

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

        while (mState == S_STATE_CONNECTED ){
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                //bytes = mmInStream.available();
                // Send the obtained bytes to the UI Activity
                if(bytes != 0) {

                }
            } catch (IOException e) {
                e.printStackTrace();

                connectionLost();

                break;
            }
        }
    }
    public void write(byte[] bytes ) {
        try {
            mmOutStream.write(bytes);
            //mmOutStream.write(bytes);
        } catch (IOException e) {
            connectionFailed();
        }
    }
    public void cancel() {
        try {
            mBTSocket.close();

        } catch (IOException e) {

        }
    }
}

Я не знаю, какполучить доступ к методу записи ConnectedThread из действия

public void write(byte[] bytes ) {
                //converts entered String into bytes
        try {
            mmOutStream.write(bytes);
            //mmOutStream.write(bytes);
        } catch (IOException e) {
            connectionFailed();
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...