1

我在调试器中查看,但我看不出有什么问题。

public class MainActivity extends Activity implements OnItemClickListener{

public BluetoothAdapter BtAdaptor;
public ArrayAdapter<String> listAdaptor;
public ArrayList<String> PairedDevices;
public ArrayList<BluetoothDevice> devices;
public ListView Lista;
public Set<BluetoothDevice> DevicesArray;
public IntentFilter filter;
public BroadcastReceiver receiver;
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
protected static final int SUCCES_CONNECT = 0;
public static final int MESSAGE_READ = 1;
public static final int MESSAGE_PRINTED = 2;
public Handler mHandler;
public InputStream mmInStream;
public OutputStream mmOutStream;
public ConnectedThread connectedThread;
public BluetoothDevice selectedDevice;
public  BluetoothSocket mmSocket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    Button scaneaza = (Button)findViewById(R.id.btnScan);
    Button printeaza = (Button)findViewById(R.id.btnSend);

    printeaza.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            ConnectThread connect = new ConnectThread(selectedDevice);
            connect.start();                
        }
    });


scaneaza.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

//          Lista.setAdapter(listAdaptor);
        startDiscovery();
        if(devices.size()!=0){
            listAdaptor.clear();
            listAdaptor.notifyDataSetChanged();
        }
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if(BluetoothDevice.ACTION_FOUND.equals(action)){
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                listAdaptor.add(device.getName()+" \n "+device);
                devices.add(device);
            }
            else   if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)){
                Toast.makeText(getApplicationContext(), "S-a terminat cautarea!", Toast.LENGTH_SHORT).show();
            }
            }
        };
        registerReceiver(receiver, filter);
        IntentFilter filter2 = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter2);
        }
    });



    BtAdaptor = BluetoothAdapter.getDefaultAdapter();

    initiere();
    if(BtAdaptor == null){
        Toast.makeText(getApplicationContext(), "Dispozitivul nu are Bt", 0).show();
    }
    else {
        if(!BtAdaptor.isEnabled()){
            Intent PornesteBt = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            Intent DescoperaBt = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
            startActivityForResult(PornesteBt,1);
            DescoperaBt.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
            startActivity(DescoperaBt);
            startDiscovery();
        }
        else {}


    }
    mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
            case SUCCES_CONNECT:
                connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_SHORT).show();
                String s="\n Mesaj trimis pt a testa.";
                connectedThread.write(s.getBytes());
                break;
            case MESSAGE_PRINTED:
                connectedThread = new ConnectedThread((BluetoothSocket)msg.obj);

                connectedThread.cancel();
                break;
            }
        }
    };
}
    private void startDiscovery() {
    BtAdaptor.cancelDiscovery();
    BtAdaptor.startDiscovery();
}

private void initiere() {
    ListView Lista = (ListView)findViewById(R.id.lView);
    Lista.setOnItemClickListener(this);
    listAdaptor = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,0);
    Lista.setAdapter(listAdaptor);
    PairedDevices = new ArrayList<String>();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    devices = new ArrayList<BluetoothDevice>();
}

@Override
protected void onDestroy() {
    super.onPause();
    unregisterReceiver(receiver);
}

@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;
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    if(BtAdaptor.isDiscovering()){
        BtAdaptor.cancelDiscovery();
    }
    Toast.makeText(getApplicationContext(), "device selectat", 0).show();
//      Object[] o= DevicesArray.toArray();
//      BluetoothDevice selectedDevice = (BluetoothDevice)o[arg2];
    selectedDevice = devices.get(arg2);

}

我使用了来自http://developer.android.com/guide/topics/connectivity/bluetooth.html的 ConnectThread 活动

private class ConnectThread extends Thread {
//      public  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
             mmSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
        } catch (IOException e) { }
//          mmSocket = tmp;
    }

    public void run() {
        // Cancel discovery because it will slow down the connection
        BtAdaptor.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)
//          manageConnectedSocket(mmSocket);
        mHandler.obtainMessage(SUCCES_CONNECT,mmSocket).sendToTarget();
    }
    /** Will cancel an in-progress connection, and close the socket */
    public void cancel() {
        Toast.makeText(getApplicationContext(), "A intrat in cancel ", Toast.LENGTH_SHORT).show();
        if(mmSocket != null){
        try {
            mmSocket.close();
        } catch (IOException e) { }
    }
}
}

And ConnectedThread... private class ConnectedThread extends Thread { // private final BluetoothSocket mmSocket;

    public ConnectedThread(BluetoothSocket socket) {
        mmSocket = socket;
//          InputStream tmpIn;
//          OutputStream tmpOut;
        try {
//              tmpIn = socket.getInputStream();
            mmInStream = socket.getInputStream();
//              tmpOut = socket.getOutputStream();
            mmOutStream = 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 {
            mHandler.obtainMessage(MESSAGE_PRINTED).sendToTarget();
            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) { }
    }
}
}

我只想作为客户端连接。谢谢。

4

0 回答 0