如何使用不同的活动从android上的蓝牙服务发送数据到arduino

时间:2018-10-12 20:10:25

标签: android android-studio bluetooth

我试图通过在一个活动中启动的蓝牙服务将数据发送到Arduino,但是要发送的数据在另一个活动中进行了处理,因为我试图从启动服务的位置发送一些数据但我没有成功。我不知道如何从服务中调用write方法。连接正确完成,这与发送数据不一样

我的服务是从活动启动的。

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

0 个答案:

没有答案