通过蓝牙发送整数或字符串 - 设备已经配对

时间:2017-06-09 19:24:40

标签: android string sockets bluetooth integer

所以我一直在研究一个应用程序,它允许我通过蓝牙发送一个简单的字符串,如“Hello”,或整数,如“2”,我已经在设备和他们之间建立了联系所有我想知道的配对是一个如何使用套接字和其他东西的示例代码,我需要通过应用程序发送内容。

我的代码到目前为止:

public class MainActivity extends Activity {
private TextView mStatusTv;
private Button mActivateBtn;
private Button mPairedBtn;
private Button mScanBtn;

private ProgressDialog mProgressDlg;

private ArrayList<BluetoothDevice> mDeviceList = new ArrayList<BluetoothDevice>();

private BluetoothAdapter mBluetoothAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    mStatusTv           = (TextView) findViewById(R.id.tv_status);
    mActivateBtn        = (Button) findViewById(R.id.btn_enable);
    mPairedBtn          = (Button) findViewById(R.id.btn_view_paired);
    mScanBtn            = (Button) findViewById(R.id.btn_scan);

    mBluetoothAdapter   = BluetoothAdapter.getDefaultAdapter();

    mProgressDlg        = new ProgressDialog(this);

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

            mBluetoothAdapter.cancelDiscovery();
        }
    });

    if (mBluetoothAdapter == null) {
        showUnsupported();
    } else {
        mPairedBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

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

                    list.addAll(pairedDevices);

                    Intent intent = new Intent(MainActivity.this, DevicelistActivity.class);

                    intent.putParcelableArrayListExtra("device.list", list);

                    startActivity(intent);
                }
            }
        });

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

        mActivateBtn.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);
                }
            }
        });

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

@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() {
    mStatusTv.setText("Bluetooth is On");


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

    mPairedBtn.setEnabled(true);
    mScanBtn.setEnabled(true);
}

private void showDisabled() {
    mStatusTv.setText("Bluetooth is Off");


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

    mPairedBtn.setEnabled(false);
    mScanBtn.setEnabled(false);
}

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

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

    mPairedBtn.setEnabled(false);
    mScanBtn.setEnabled(false);
}

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

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)) {
            mDeviceList = new ArrayList<BluetoothDevice>();

            mProgressDlg.show();
        } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
            mProgressDlg.dismiss();

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

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

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

            mDeviceList.add(device);

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

设备清单:

public class DevicelistActivity extends Activity {
private ListView mListView;
private Adapter mAdapter;
private ArrayList<BluetoothDevice> mDeviceList;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_devicelist);

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

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

    mAdapter        = new Adapter(this);

    mAdapter.setData(mDeviceList);
    mAdapter.setListener(new Adapter.OnPairButtonClickListener() {
        @Override
        public void onPairButtonClick(int position) {
            BluetoothDevice device = mDeviceList.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));
}

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

    super.onDestroy();
}


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

private void pairDevice(BluetoothDevice device) {
    try {
        Method method = device.getClass().getMethod("createBond", (Class[]) null);
        method.invoke(device, (Object[]) null);
    } 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();
    }
}

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");


                Intent transmit = new Intent(DevicelistActivity.this,transmission.class);
                startActivity(transmit);



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

            mAdapter.notifyDataSetChanged();
        }
    }
};}

适配器:

public class Adapter extends BaseAdapter{
private LayoutInflater mInflater;
private List<BluetoothDevice> mData;
private OnPairButtonClickListener mListener;



public Adapter(Context context) {
    mInflater = LayoutInflater.from(context);
}

public void setData(List<BluetoothDevice> data) {
    mData = data;
}

public void setListener(OnPairButtonClickListener listener) {
    mListener = listener;
}

public int getCount() {
    return (mData == null) ? 0 : mData.size();
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        convertView         =  mInflater.inflate(R.layout.activity_adapter, null);

        holder              = new ViewHolder();

        holder.nameTv       = (TextView) convertView.findViewById(R.id.tv_name);
        holder.addressTv    = (TextView) convertView.findViewById(R.id.tv_address);
        holder.pairBtn      = (Button) convertView.findViewById(R.id.btn_pair);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    BluetoothDevice device  = mData.get(position);

    holder.nameTv.setText(device.getName());
    holder.addressTv.setText(device.getAddress());
    holder.pairBtn.setText((device.getBondState() == BluetoothDevice.BOND_BONDED) ? "Unpair" : "Pair");
    holder.pairBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (mListener != null) {
                mListener.onPairButtonClick(position);
            }
        }
    });

    return convertView;
}

static class ViewHolder {
    TextView nameTv;
    TextView addressTv;
    TextView pairBtn;
}

public interface OnPairButtonClickListener {
    public abstract void onPairButtonClick(int position);
}

因此,当您看到我在deviceList活动中构建一个Intent时,它会将我移动到一个新活动,该活动应该有一个编辑文本,用于填充将要发送到配对设备的数字或文本,< / p>

请帮助我完成我所指的新活动,我们非常感谢任何代码或建议!谢谢stackoverflow社区!

ps:其他设备不一定是手机,它也可以是微型AVR或arduino但这不是问题,我只是想知道如何使用连接和发送数据,请防止发送谷歌链接cuz我已经搜索了很多,这很复杂!

0 个答案:

没有答案