1

修繕!!!

api15以降のUUIDが原因で機能しませんでした.get関数を使用してuuidを取得できます

UID uuid = bluetoothDevice.getUuids()[0].getUuid(); 
BluetoothSocket socket = bluetoothDevice.createRfcommSocketToServiceRecord(uuid);

修繕!!!

デバイスに接続してデータを書き込もうとしています。デバイスを検索できます。クリックすると接続スレッドが開始されますが、「run()」関数は呼び出されません。プログラムが動かなくなった

現在、Bluetoothヘッドセットに接続しようとしています。2 つのデバイスをペアリングしているかどうかわかりません。電話の通常のBluetoothを使用する場合、1 2 3 4のようなコードで2つのデバイスをペアリングしていますが、私のプログラムではコードを入力する必要はありません. 助けてくれませんか?

mmSocket.connect();

したがって、私の connectedthread() は決して実行されません!

ここに私の完全なコードがあります:

public class MainActivity extends Activity {

private static final int REQUEST_ENABLE_BT = 1;
private BluetoothAdapter mBluetoothAdapter = null;
private ArrayAdapter<String> mNewDevicesArrayAdapter;
ListView newDevicesListView;
   // Return Intent extra
public static String EXTRA_DEVICE_ADDRESS = "device_address";
private ConnectingDevices mConnectingDevices = null;


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

    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

    newDevicesListView = (ListView)findViewById(R.id.new_devices);
    mNewDevicesArrayAdapter=new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1);
    newDevicesListView.setAdapter(mNewDevicesArrayAdapter);
    newDevicesListView.setOnItemClickListener(mDeviceClickListener);

    registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));

    mConnectingDevices = new ConnectingDevices();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) 
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

public void onClickbtnEtage1(View view)
{
mConnectingDevices.write(new byte[2]);
}


public void onClickbtnActivateBluetooth(View view)
{

      if (mBluetoothAdapter == null) 
      {
            Toast.makeText(this, "Bluetooth ist nicht verfügbar!", Toast.LENGTH_LONG).show();
            finish();
            return;
      }
      else if (!mBluetoothAdapter.isEnabled()) 
      {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
      }
      Toast.makeText(this, "Bluetooth wurde aktiviert!", Toast.LENGTH_LONG).show();
      findViewById(R.id.btnSearchDevices).setEnabled(true);


}

public void onClickbtnSearchDevices(View view)
{
    mBluetoothAdapter.startDiscovery();
    Toast.makeText(this, "Bluetooth Geräte werden gesucht!", Toast.LENGTH_LONG).show();
      // Find and set up the ListView for newly discovered devices 
}

// Create a BroadcastReceiver for ACTION_FOUND
 private final BroadcastReceiver mReceiver = 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);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) 
                {
                    mNewDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                    mNewDevicesArrayAdapter.notifyDataSetChanged();

                }


            }
        }
    };

    // The on-click listener for all devices in the ListViews
    private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
        public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
            // Cancel discovery because it's costly and we're about to connect
            mBluetoothAdapter.cancelDiscovery();

            // Get the device MAC address, which is the last 17 chars in the View
            String info = ((TextView) v).getText().toString();
            String address = info.substring(info.length() - 17);

            // Create the result Intent and include the MAC address
            Intent intent = new Intent();
            intent.putExtra(EXTRA_DEVICE_ADDRESS, address);
            // Set result and finish this Activity
        //    setResult(Activity.RESULT_OK, intent);
          // finish();



                address = intent.getExtras().getString(EXTRA_DEVICE_ADDRESS);
                // Get the BLuetoothDevice object
                BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
                // Attempt to connect to the device
                mConnectingDevices.connect(device);


        }

    };}

そして私のconnectingdevicesクラス

        public class ConnectingDevices {

boolean bconnectedthread = false;
boolean bconnectthread = false;
boolean bconnectedthreadstart = false;
boolean bconnectthreadstart = false;
boolean brun=false;
boolean bconnectedsynchronized=false;
//00001108-0000-1000-8000-00805F9B34FB
    private BluetoothAdapter mBluetoothAdapter = null;
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private ConnectedThread mConnectedThread;
    //private final Handler mHandler;
    private ConnectThread mConnectThread;

    public void write(byte[] out) {
        boolean a=bconnectedthread;
        boolean b=bconnectthread;
        boolean c=bconnectedthreadstart;
        boolean d=bconnectthreadstart;
        boolean e=brun;
        boolean f=bconnectedsynchronized;

        // Create temporary object
        ConnectedThread r;
        // Synchronize a copy of the ConnectedThread
        synchronized (this) {

            r = mConnectedThread;
        }
        // Perform the write unsynchronized
        r.write(out);

    }

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;
        bconnectthread = true;

        // 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
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        mBluetoothAdapter.cancelDiscovery();
       brun=true;
        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)
        //bconnectedthreadstart = true;

       connected(mmSocket);

    }

    /** 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;
        bconnectedthread=true;

        // 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);
                // 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) { }
    }
}


public synchronized void connect(BluetoothDevice device) 

{  
    bconnectthreadstart=true;
    mConnectThread = new ConnectThread(device);
    mConnectThread.start();

}


public synchronized void connected(BluetoothSocket socket) {

    bconnectedsynchronized=true;
    mConnectedThread = new ConnectedThread(socket);
    mConnectedThread.start();


}}



logcat
    05-21 17:49:29.902: W/dalvikvm(25720): threadid=1: thread exiting with uncaught exception (group=0x417da498)
    05-21 17:49:29.912: E/AndroidRuntime(25720): FATAL EXCEPTION: main
    05-21 17:49:29.912: E/AndroidRuntime(25720): java.lang.IllegalStateException: Could not execute method of the activity
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.view.View$1.onClick(View.java:3676)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.view.View.performClick(View.java:4171)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.view.View$PerformClick.run(View.java:17070)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.os.Handler.handleCallback(Handler.java:615)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.os.Handler.dispatchMessage(Handler.java:92)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.os.Looper.loop(Looper.java:137)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.app.ActivityThread.main(ActivityThread.java:4797)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at java.lang.reflect.Method.invokeNative(Native Method)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at java.lang.reflect.Method.invoke(Method.java:511)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:804)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:571)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at dalvik.system.NativeStart.main(Native Method)
    05-21 17:49:29.912: E/AndroidRuntime(25720): Caused by: java.lang.reflect.InvocationTargetException
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at java.lang.reflect.Method.invokeNative(Native Method)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at java.lang.reflect.Method.invoke(Method.java:511)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at android.view.View$1.onClick(View.java:3671)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    ... 11 more
    05-21 17:49:29.912: E/AndroidRuntime(25720): Caused by: java.lang.NullPointerException
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at com.example.elevator.ConnectingDevices.write(ConnectingDevices.java:40)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    at com.example.elevator.MainActivity.onClickbtnEtage1(MainActivity.java:63)
    05-21 17:49:29.912: E/AndroidRuntime(25720):    ... 14 more
    05-21 17:49:49.062: I/System.out(27064): Debugger has connected
    05-21 17:49:49.062: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:49.262: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:49.472: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:49.663: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:49.863: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:50.063: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:50.263: I/System.out(27064): waiting for debugger to settle...
    05-21 17:49:50.474: I/System.out(27064): debugger has settled (1455)
    05-21 17:49:50.684: W/ResourceType(27064): No package identifier when getting value for resource number 0x00000000
    05-21 17:49:50.684: W/PackageManager(27064): Failure retrieving resources forcom.example.elevator: Resource ID #0x0
    05-21 17:49:50.944: D/IconCustomizer(27064): Generate customized icon for com.example.elevator.png
    05-21 17:49:50.984: W/IconCustomizer(27064): can't load transform_config.xml
    05-21 17:49:51.164: I/themeservice(27064): add pending job /data/data/com.example.elevator/cache/com.example.elevator.png
    05-21 17:49:51.174: I/themeservice(27064): binding service
    05-21 17:49:51.344: I/themeservice(27064): service connected
    05-21 17:49:51.344: I/themeservice(27064): saving icon for /data/data/com.example.elevator/cache/com.example.elevator.png
    05-21 17:49:51.415: I/Adreno200-EGL(27064): <qeglDrvAPI_eglInitialize:294>: EGL 1.4 QUALCOMM build:  (CL3068996)
    05-21 17:49:51.415: I/Adreno200-EGL(27064): Build Date: 03/07/13 Thu
    05-21 17:49:51.415: I/Adreno200-EGL(27064): Local Branch: au37
    05-21 17:49:51.415: I/Adreno200-EGL(27064): Remote Branch: 
    05-21 17:49:51.415: I/Adreno200-EGL(27064): Local Patches: 
    05-21 17:49:51.415: I/Adreno200-EGL(27064): Reconstruct Branch: 
    05-21 17:49:52.346: I/themeservice(27064): unbinding service
    05-21 17:50:36.903: I/ConnectingDevices(27064): connectthread function started
    05-21 17:50:36.903: I/ConnectingDevices(27064): connectthread is working
    05-21 17:50:36.913: I/ConnectingDevices(27064): connectthread is running
    05-21 17:50:36.953: E/ConnectingDevices(27064): mmSocket unable to connect
    05-21 17:50:36.953: E/ConnectingDevices(27064): java.io.IOException: Unable to start Service Discovery
    05-21 17:50:36.953: E/ConnectingDevices(27064):     at android.bluetooth.BluetoothSocket$SdpHelper.doSdp(BluetoothSocket.java:455)
    05-21 17:50:36.953: E/ConnectingDevices(27064):     at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:230)
    05-21 17:50:36.953: E/ConnectingDevices(27064):     at com.example.elevator.ConnectingDevices$ConnectThread.run(ConnectingDevices.java:77)
4

0 に答える 0