监控android中两个设备之间的蓝牙连接

时间:2016-01-18 10:25:22

标签: android android-bluetooth

在我的Android应用程序中,我需要监控配对设备之间的连接,因此一旦连接丢失或其他设备Bluetooth关闭,我想提醒用户。我使用了BluetoothDevice.ACTION_ACL_DISCONNECTED ,BluetoothDevice.ACTION_ACL_CONNECTED,但它没有用!

请问如何发送有关连接状态的通知(仍然是已连接,已断开连接)?任何帮助将不胜感激

这是我的代码

MainActivity

public class MainActivity extends Activity
{
private TextView StatusTv;
private Button ActivateBtn;

private Button PairedBtn;
private Button ScanBtn;

private ProgressDialog ProgressDlg;

private ArrayList<BluetoothDevice> ScannedNearbyDevicesList = new ArrayList<BluetoothDevice>();
private BluetoothAdapter mBluetoothAdapter;

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

    StatusTv            = (TextView) findViewById(R.id.tv_status);
    ActivateBtn         = (Button) findViewById(R.id.btn_enable);

    PairedBtn           = (Button) findViewById(R.id.btn_view_paired);
    ScanBtn             = (Button) findViewById(R.id.btn_scan);

    mBluetoothAdapter   = BluetoothAdapter.getDefaultAdapter();


    if (mBluetoothAdapter == null)
    {
        showUnsupported();

    } 
    else
    {


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

                if (mBluetoothAdapter.isEnabled())
                {
                    mBluetoothAdapter.disable();
                    showDisabled();
                }
                else
                {
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 1000);
                }
            }
        });


        ScanBtn.setOnClickListener(new View.OnClickListener() {             
            @Override
            public void onClick(View arg0)
            {
                mBluetoothAdapter.startDiscovery();
            }
        });

        ProgressDlg         = new ProgressDialog(this);
        ProgressDlg.setMessage("Scanning...");
        ProgressDlg.setCancelable(false);
        ProgressDlg.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();

                mBluetoothAdapter.cancelDiscovery();
            }
        });


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

                Set<BluetoothDevice> pairedDevicesSet = mBluetoothAdapter.getBondedDevices();

                if (pairedDevicesSet == null || pairedDevicesSet.size() == 0)
                { 
                    showToast("No Paired Devices Found");
                } 
                else 
                {
                    ArrayList<BluetoothDevice> pairedDevicesList = new ArrayList<BluetoothDevice>();

                    pairedDevicesList.addAll(pairedDevicesSet);


                    Intent intent = new Intent(MainActivity.this, DevicesListActivity.class);
                    intent.putParcelableArrayListExtra("device.list", pairedDevicesList);
                    startActivity(intent);                      
                }
            }
        });




        if (mBluetoothAdapter.isEnabled())
        {
            showEnabled();
        }
       else {  showDisabled();  }


    }

    IntentFilter filter = new IntentFilter();

    filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
    filter.addAction(BluetoothDevice.ACTION_FOUND);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
    filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

    registerReceiver(mReceiver, filter);






   }


    private final BroadcastReceiver mReceiver = new BroadcastReceiver() 
    {
        public void onReceive(Context context, Intent intent)
        {           
            String action = intent.getAction();


            if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action))
            {
                final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);

                if (state == BluetoothAdapter.STATE_ON)
                {

                    showToast("Enabled");
                    showEnabled();
                 }
            } 


            else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action))
            {
                ScannedNearbyDevicesList = new ArrayList<BluetoothDevice>();

                ProgressDlg.show();

            } 

            else if (BluetoothDevice.ACTION_FOUND.equals(action))
            {
                BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                ScannedNearbyDevicesList.add(device);
                showToast("Found device " + device.getName());
            }


            else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action))
            {
                ProgressDlg.dismiss();


                Intent newIntent = new Intent(MainActivity.this, DevicesListActivity.class);

                newIntent.putParcelableArrayListExtra("device.list", ScannedNearbyDevicesList);

                startActivity(newIntent);
            } 




        }


     };





@Override
public void onPause()
{
    if (mBluetoothAdapter != null) {
        if (mBluetoothAdapter.isDiscovering()) {
            mBluetoothAdapter.cancelDiscovery();
        }
    }

    super.onPause();
}

@Override
public void onDestroy()
{
    unregisterReceiver(mReceiver);

    super.onDestroy();
}

private void showEnabled()
{
    StatusTv.setText("Bluetooth is On");
    StatusTv.setTextColor(Color.BLUE);

    ActivateBtn.setText("Disable");     
    ActivateBtn.setEnabled(true);

    PairedBtn.setEnabled(true);
    ScanBtn.setEnabled(true);
}

private void showDisabled() 
{
    StatusTv.setText("Bluetooth is Off");
    StatusTv.setTextColor(Color.RED);

    ActivateBtn.setText("Enable");
    ActivateBtn.setEnabled(true);

    PairedBtn.setEnabled(false);
    ScanBtn.setEnabled(false);
}

private void showUnsupported() 
{
    StatusTv.setText("Bluetooth is unsupported by this device");

    ActivateBtn.setText("Enable");
    ActivateBtn.setEnabled(false);

    PairedBtn.setEnabled(false);
    ScanBtn.setEnabled(false);
}

private void showToast(String message)
{
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
}






 }

DevicesListActivity

public class DevicesListActivity extends Activity 
{
  private ListView mListView;
private DeviceListAdapter mAdapter;

private ArrayList<BluetoothDevice> PassedDeviceList;

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_devices_list);

    PassedDeviceList        = getIntent().getExtras().getParcelableArrayList("device.list");

    mListView       = (ListView) findViewById(R.id.DevicesList_lv);

    mAdapter        = new DeviceListAdapter(this);
    mAdapter.setData(PassedDeviceList);

    //When User Click PairBTN  For Specific Device 
    mAdapter.setListener(new DeviceListAdapter.OnPairButtonClickListener() {            
        @Override
        public void onPairButtonClick(int position)
        {

            showToast("PairedBTN Clicked");
            BluetoothDevice device = PassedDeviceList.get(position);


            if (device.getBondState() == BluetoothDevice.BOND_BONDED)
            {
                unpairDevice(device);
            }

            else 
            {
                showToast("Pairing...");
                pairDevice(device);
            }
        }
    });

    mListView.setAdapter(mAdapter);

    registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)); 



    registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
    registerReceiver(mPairReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));


}



private void pairDevice(final BluetoothDevice device)
{
    try 
    {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

        registerReceiver(mPairReceiver, new IntentFilter(device.ACTION_ACL_CONNECTED));
        registerReceiver(mPairReceiver, new IntentFilter(device.ACTION_ACL_DISCONNECTED));




    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

}

private void unpairDevice(BluetoothDevice device)
{
    try
    {
        Method method = device.getClass().getMethod("removeBond", (Class[]) null);
        method.invoke(device, (Object[]) null);

    }
    catch (Exception e)
    {
        e.printStackTrace();
    }
}


//To Track  Pairing Status  with Device
private final BroadcastReceiver mPairReceiver = new BroadcastReceiver() {

    public void onReceive(Context context, Intent intent)
    {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action))
        {               
             final int state        = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR);
             final int prevState    = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR);

             if(state == BluetoothDevice.BOND_BONDED && prevState == BluetoothDevice.BOND_BONDING)
             {
                 showToast("Paired");
             }
             else if (state == BluetoothDevice.BOND_NONE && prevState == BluetoothDevice.BOND_BONDED)
             {
                 showToast("Unpaired");
             }


            if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
            {
                //Do something if connected
                showToast( "the  Connection is continued ");
            }
            if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) 
            {
                //Do something if disconnected
                showToast( " Disconnected !!! ");
            }
           if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) 
            {
                //Do something if disconnect Req is done
                showToast( " Disconnect Request is Sent");
            }


         //********************************************************************* 

             mAdapter.notifyDataSetChanged();
        }



    }




};



private final BroadcastReceiver monitorConnReceiver= new BroadcastReceiver(){

    public void onReceive(Context context, Intent intent)
    {

        String action = intent.getAction();

        final int state         = intent.getIntExtra(BluetoothDevice.ACTION_ACL_DISCONNECTED, BluetoothDevice.ERROR);

        showToast( " Device State :: "+ state);

        //******* To Monitor the Conn. Status with the Paired Device *******
        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action))
        {
            //Do something if connected
            showToast( "the  Connection is continued ");
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) 
        {
            //Do something if disconnected
            showToast( " Disconnected !!! ");
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) 
        {
            //Do something if disconnect Req is done
            showToast( " Disconnect Request is Sent");
        }


    }


};

@Override
public void onDestroy() {
    unregisterReceiver(mPairReceiver);

    super.onDestroy();
}


private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG ).show();
}

}

0 个答案:

没有答案