1

大家好, 在我的应用程序中,我只想发送数据 2.3.3 及更高版本的 android 欺骗,但是当我开始发现蓝牙设备时,我的应用程序会获取所有已激活的设备。

这些设备都是android和其他设备。我如何过滤或了解具有2.3.3或更高版本的设备

我的代码如下:

公共类 MainActivity 扩展 Activity 实现 OnItemClickListener {

Button mBtnConnect;
ListView mlist;
BluetoothAdapter mBluetoothAdapter;

IntentFilter filter;

MyBluetoothAdapter blu_adapter=null;

Set<BluetoothDevice> deviceArray;
ArrayList<String> pairedDevices;
ArrayList<String> pairedDevices_list;
ArrayList<String> bonded_list;

ArrayList<BluetoothDevice> Devices;


public static final UUID MY_UUID =  UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
protected static final int SUCCESS_CONNECT = 0;
protected static final int MESSAGE_READ=1;


Handler mHandler=new Handler() {

    public void handleMessage(Message msg) {

        super.handleMessage(msg);

        switch (SUCCESS_CONNECT) {

        case SUCCESS_CONNECT:
            ConnectedThread connecteThread=new ConnectedThread((BluetoothSocket)msg.obj);
            Toast.makeText(getApplicationContext(), "Connected", 0).show();

            String s="successfully connected ";
            connecteThread.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.activity_main);

    initilizeField();


    if (mBluetoothAdapter == null) {
        Toast.makeText(getApplicationContext(),
                "No bluetooth device found", 0).show();
        finish();
    }

    else {
        if (!mBluetoothAdapter.isEnabled()) {

            TurnonBT();

        }
        getPairedDevices();
        StartDiscovery();

    }

    mBtnConnect.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub



            blu_adapter=new MyBluetoothAdapter(MainActivity.this, pairedDevices,bonded_list);
            mlist.setAdapter(blu_adapter);



        }
    });




}

private void StartDiscovery() {
    // TODO Auto-generated method stub


    mBluetoothAdapter.cancelDiscovery();
    mBluetoothAdapter.startDiscovery();
}

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

private void initilizeField() {
    // TODO Auto-generated method stub




    mlist = (ListView) findViewById(R.id.listView);
    mBtnConnect = (Button) findViewById(R.id.mBtnConnect);
    mlist = (ListView) findViewById(R.id.listView);

    pairedDevices = new ArrayList<String>();
    pairedDevices_list = new ArrayList<String>();
    bonded_list=new ArrayList<String>();
    Devices=new ArrayList<BluetoothDevice>();
    /*listAdapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1, 0);

    mlist.setAdapter(listAdapter);*/

    //click listner
    mlist.setOnItemClickListener(this);


    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

     Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
     discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 400);
     startActivity(discoverableIntent);
     Toast.makeText(getApplicationContext(), "Now your device is discoverable by others", Toast.LENGTH_LONG).show();





    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    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);

    // deviceArray=new

}

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_FOUND.equals(action)) {

            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

            Devices.add(device);





        //- listAdapter.add(device.getName() + " "+s+" "+"\n"+ device.getAddress());

            for (BluetoothDevice  devicePaired : Devices) {
                if(bonded_list.contains(devicePaired)){

                }
                else{
                    bonded_list.add("Not Paired");
                }

            }
            if(pairedDevices.contains(device.getName())){

            }
            else{
                pairedDevices.add(device.getName());
            }


        } else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {

        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {

        /*  if(listAdapter.getCount()>0){

                for(int i=0;i<listAdapter.getCount();i++){

                    for(int a=0;a<pairedDevices.size();a++){

                        if(listAdapter.getItem(i).equals(pairedDevices.get(a))){

                        }

                    }

                }
            }*/

        } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {

            if(mBluetoothAdapter.getState()==mBluetoothAdapter.STATE_OFF){
                TurnonBT();
            }
        }

    }
};
private void getPairedDevices() {
    // TODO Auto-generated method stub

    deviceArray = mBluetoothAdapter.getBondedDevices();

    if (deviceArray.size() > 0) {

        for (BluetoothDevice device : deviceArray) {


            if(pairedDevices.contains(device.getName())){


                //device already in paired array list
            }
            else{
            pairedDevices.add(device.getName());

            bonded_list.add("Paired");
            }

        }
    }
}

@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 enable to connect", Toast.LENGTH_SHORT)
                .show();
        finish();

    }
}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();


    getPairedDevices();
    StartDiscovery();


    /*filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

    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);*/

    //unregisterReceiver(receiver);
}
 @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mBluetoothAdapter != null) {
        mBluetoothAdapter.cancelDiscovery();
    }
    unregisterReceiver(receiver);
  }
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    // TODO Auto-generated method stub

    if(mBluetoothAdapter.isDiscovering()){
        mBluetoothAdapter.cancelDiscovery();
    }
    if(bonded_list.get(position).contains("Paired")){
        //Toast.makeText(getApplicationContext(), "This device is already paired", 0).show();

        //Object[] o=deviceArray.toArray();

        BluetoothDevice selectedDevices=Devices.get(position);

        ConnectThread connect=new ConnectThread(selectedDevices);
        connect.start();
    }
    else{
        Toast.makeText(getApplicationContext(), "This 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
        mBluetoothAdapter.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(SUCCESS_CONNECT,mmSocket).sendToTarget();
    }

    private void manageConnectedSocket(BluetoothSocket mmSocket2) {
        // TODO Auto-generated method stub

    }

    /** 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 {
                // Read from the InputStream
                 buffer= new byte[1024];
                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) { }
    }
}
}
4

1 回答 1

0
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.FROYO){
    // Do something for froyo and above versions
} else{
    // do something for phones running an SDK before froyo
}
于 2013-10-23T13:02:30.670 回答