Android-приложение для связи по Bluetooth

Я написал заявку на наш проект.

Я написал это, когда смотрел урок на ютубе.

Это для связи через блютуз.

Устройство связывается и подключается к устройству, и устройство отправляет строку Successful Connected обратно на терминал.

Но данные, которые я отправил, не получены устройством (для отображения полученных данных используется всплывающее сообщение).

Пожалуйста, уточните, и это мой код

public class MainActivity extends Activity implements OnItemClickListener {

protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ = 1;
ArrayAdapter<String> listAdapter;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
ArrayList<String> pairedDevices;
IntentFilter filter;
BroadcastReceiver receiver;
String tag = "debugging";
ArrayList<BluetoothDevice> devices;
public static UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

Handler mHandler = new Handler(){
    public void handleMessage(android.os.Message msg) {
        switch(msg.what){
        case SUCCESS_CONNECT:
            ConnectedThread connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "Successfully Connected", 0).show();
            String s = "Successfully Connected";
            connectedThread.write(s.getBytes());
            break;
        case MESSAGE_READ:
            byte[] readbuf = (byte[])msg.obj;
            String string = new String(readbuf);
            Toast.makeText(getApplicationContext(), string, 0).show();
            break;
        }
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    init();
    if(btAdapter == null){
        Toast.makeText(getApplicationContext(), "No Bluetooth Detected", 0).show();
        finish();
    }
    else{
        if(!btAdapter.isEnabled()){
            turnOnBT();
        }
        getPairedDevices();
        startDiscovery();
    }
}

private void startDiscovery() {
    // TODO Auto-generated method stub
    btAdapter.cancelDiscovery();
    btAdapter.startDiscovery();
}

private void turnOnBT() {
    // TODO Auto-generated method stub
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivityForResult(intent, 1);
}

private void getPairedDevices() {
    // TODO Auto-generated method stub
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device: devicesArray){
            pairedDevices.add(device.getName());
        }
    }
}


//initializes all the variables
private void init() {
    // TODO Auto-generated method stub
    listView = (ListView)findViewById(R.id.listView);
    listView.setOnItemClickListener(this);
    listAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);
    btAdapter = BluetoothAdapter.getDefaultAdapter();
    pairedDevices = new ArrayList<String>();
    devices = new ArrayList<BluetoothDevice>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                devices.add(device);
                String s = "";
                for(int i = 0 ; i< pairedDevices.size(); i++){
                    if(device.getName().equals(pairedDevices.get(i))){
                        s ="(PAIRED)";
                        break;                          
                    }
                }
                listAdapter.add(device.getName()+" "+s+"\n"+device.getAddress());
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)){
                //some code
            }
            else if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                //some code
            }
            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }
        }
    };
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
    registerReceiver(receiver, filter);
    filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
    registerReceiver(receiver, filter);
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    unregisterReceiver(receiver);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == RESULT_CANCELED){
        Toast.makeText(getApplicationContext(), "Bluetooth must be enabled", Toast.LENGTH_SHORT).show();
        finish();
    }
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
//public abstract void onItemClick (AdapterView<?> parent, View view, int position, long id)
    // TODO Auto-generated method stub
    if(btAdapter.isDiscovering()){
        btAdapter.cancelDiscovery();
    }
    if(listAdapter.getItem(arg2).contains("(PAIRED)")){
        //Toast.makeText(getApplicationContext(), "Device is Already Paired", 0).show();
        BluetoothDevice selectedDevice = devices.get(arg2);
        ConnectThread connect = new ConnectThread(selectedDevice);
        connect.start();
        Log.i(tag,"in click listener");
    }
    else{
        Toast.makeText(getApplicationContext(), "Device is not Paired", 0).show();
    }
}

private class ConnectThread extends Thread {

    private final BluetoothSocket mmSocket;
    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        BluetoothSocket tmp = null;
        mmDevice = device;

        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
        mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        btAdapter.cancelDiscovery();

        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket.connect();
        } catch (IOException connectException) {
            // Unable to connect; close the socket and get out
            try {
                mmSocket.close();
            } catch (IOException closeException) { }
            return;
        }

        // Do work to manage the connection (in a separate thread)

        mHandler.obtainMessage(SUCCESS_CONNECT,mmSocket).sendToTarget();
    }

    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
private class ConnectedThread extends Thread {
    private final BluetoothSocket mmSocket;
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

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

        // Get the input and output streams, using temp objects because
        // member streams are final
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }

    public void run() {
        byte[] buffer;  // buffer store for the stream
        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            try {
                buffer = new byte[1024];
                // Read from the InputStream
                bytes = mmInStream.read(buffer);
                // Send the obtained bytes to the UI activity
                mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    /* Call this from the main activity to send data to the remote device */
    public void write(byte[] bytes) {
        try {
            mmOutStream.write(bytes);
        } catch (IOException e) { }
       }

    /* Call this from the main activity to shutdown the connection */
    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) { }
     }
   }
}

person Adeesha Savinda de Silva    schedule 26.08.2014    source источник
comment
Вы получаете какое-то сообщение об ошибке? Отображается всплывающее сообщение? Тоже теряется? Пожалуйста, будьте немного более конкретными, просто вставка вашего кода не сильно поможет.   -  person Nahuel Ianni    schedule 26.08.2014
comment
Нет сообщения об ошибке. Тост, отображающий только успешное подключение, можно увидеть на моем устройстве. Извините, я плохо разбираюсь в андроиде. Поэтому я не могу сказать об этом конкретно. Есть ли какое-то отношение к объявлению Handler mHandler?   -  person Adeesha Savinda de Silva    schedule 26.08.2014
comment
Пожалуйста, если вы можете найти кодировку и дать объяснение, это было бы очень полезно. Извините за беспокойство   -  person Adeesha Savinda de Silva    schedule 26.08.2014


Ответы (1)


При подключении к модулю Bluetooth получите адрес из объекта BluetoothDevice. Используйте следующий пример кода для подключения к устройству Bluetooth. Он работает для меня.

for(BluetoothDevice bt: mBluetoothAdapter.getBondedDevices()) {
    if(bt.getName().equalsIgnoreCase(selectedBTDeviceName)) {
        BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(bt.getAddress());
        mBluetoothAdapter.cancelDiscovery();

        mBSocket = device.createRfcommSocketToServiceRecord(SPP_UUID);
        mBSocket.connect();
        return mBSocket;
    }
}

Вы создали объект BluetoothDevice, используя метод device.getAddress(). Теперь единственная возможная проблема, которую я вижу, заключается в вашем BroadcastReceiver.

В методе init(), который вы вызвали из onCreate(), вы регистрируете BroadcastReceiver с помощью это действие и в onPause() вы отменили регистрацию BroadcastReceiver.

Зарегистрируйте его в своем методе onResume(), чтобы вы могли получать трансляцию всякий раз, когда вы возобновляете это действие.

person RaiVikrant    schedule 07.02.2015