На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: Hsilgos
  
> Android планшет, ошибка при создании BluetoothSocket
    Доброго дня форумчане, давно тут не был, да вот случилась трабла и вспомнил :).

    Решил написать под Android приложение которое будет собирать данные по Bluetooth с моего устройства и отображать их в виде графиков. Поиск устройства работает, но при попытке создать BluetoothSocket приложение вылетает и все, даже в дебаггере ничего не пишет. Есть ли знатоки сего дела, помогите.

    Добавлено
    ExpandedWrap disabled
      public class MainActivity extends AppCompatActivity {
       
          ArrayList<String> listItems=new ArrayList<String>();
          ArrayAdapter<String> adapter;
          private TextView mReadBuffer;
       
          private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();
          private BluetoothAdapter mBluetoothAdapter;
          private String selectedConn;
       
          private Handler mHandler; // Our main handler that will receive callback notifications
          private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
          private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
       
          private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
       
       
          // #defines for identifying shared types between calling functions
          private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
          private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
          private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
       
          private ListView list;
       
          @Override
          protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.activity_main);
       
              list = (ListView) findViewById(R.id.listView);
              mReadBuffer = (TextView) findViewById(R.id.readBuffer);
       
              list.setOnItemClickListener(new OnItemClickListener() {
                  @Override
                  public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                      selectedConn = (String) list.getItemAtPosition(position);
                  }
              });
       
              mBluetoothAdapter   = BluetoothAdapter.getDefaultAdapter();
       
              adapter=new ArrayAdapter<String>(this,
                      android.R.layout.simple_list_item_1,
                      listItems);
              list.setAdapter(adapter);
       
              mHandler = new Handler(){
                  public void handleMessage(android.os.Message msg){
                      if(msg.what == MESSAGE_READ){
                          String readMessage = null;
                          try {
                              readMessage = new String((byte[]) msg.obj, "UTF-8");
                          } catch (UnsupportedEncodingException e) {
                              e.printStackTrace();
                          }
                          mReadBuffer.setText(readMessage);
                      }
                  }
              };
       
          }
       
          public void butRefresh_Click(View v){
              Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
              startActivityForResult(turnOn, 0);
              Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
       
              for(BluetoothDevice bt : pairedDevices)
                  listItems.add(bt.getName());
       
              adapter.notifyDataSetChanged();
          }
       
          public void butConnect_Click(View v){
              Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
              String tmpAddress = null;
               for (BluetoothDevice bt : pairedDevices) {
                  if(bt.getName().equals(selectedConn)){
                      tmpAddress = bt.getAddress();
                      break;
                  }
              }
       
              if(tmpAddress != null){
                  final String address = tmpAddress;
                  final String name = selectedConn;
                  new Thread()
                  {
                      public void run() {
                          boolean fail = false;
       
                          BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
       
                          try {
                              mBTSocket = createBluetoothSocket(device);
                          } catch (IOException e) {
                              fail = true;
                              Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                          }
                          // Establish the Bluetooth socket connection.
                          try {
                              mBTSocket.connect();
                          } catch (IOException e) {
                              try {
                                  fail = true;
                                  mBTSocket.close();
                                  mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
                                          .sendToTarget();
                              } catch (IOException e2) {
                                  //insert code to deal with this
                                  Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
                              }
                          }
                          if(fail == false) {
                              mConnectedThread = new ConnectedThread(mBTSocket);
                              mConnectedThread.start();
       
                              mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
                                      .sendToTarget();
                          }
                      }
                  }.start();
              }else{
                  Toast.makeText(getBaseContext(), "Can't find address", Toast.LENGTH_SHORT).show();
              }
          }
          private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
              return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
              //creates secure outgoing connection with BT device using UUID
          }
       
          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 = new byte[1024];  // buffer store for the stream
                  int bytes; // bytes returned from read()
       
                  // Keep listening to the InputStream until an exception occurs
                  while (true) {
                      try {
                          // Read from the InputStream
                          bytes = mmInStream.read(buffer);
                          if(bytes != 0) {
                              SystemClock.sleep(100);
                              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(String input) {
                  byte[] bytes = input.getBytes();           //converts entered String into 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) { }
              }
          }
      }


    код надерган по большей части из разных примеров, так что не сильно ругайтесь, я еще только начинаю познавать мир жабы и дроида )))
    Сообщение отредактировано: Pit-Bul -
    0 пользователей читают эту тему (0 гостей и 0 скрытых пользователей)
    0 пользователей:


    Рейтинг@Mail.ru
    [ Script execution time: 0,0199 ]   [ 16 queries used ]   [ Generated: 19.04.24, 19:40 GMT ]