如何添加像弹出菜单一样的小圆圈(如滚动和显示文字连接),当移动到该特定项目后,它应该成功显示已连接/断开连接(连接时)。以下是我的设备扫描活动。在此我将获得所有ble设备的列表。这是我的设备安全性
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setTitle("BLE Devices");
UUIDS=new UUID[]{(UUID.fromString("0000180f-0000-1000-8000-00805f9b34fb")) };
mHandler = new Handler();
db = new DataBaseAdapter(this);
// Use this check to determine whether BLE is supported on the device. Then you can
// selectively disable BLE-related features.
if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
// Initializes a Bluetooth adapter. For API level 18 and above, get a reference to
// BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager =
(BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
// Checks if Bluetooth is supported on the device.
if (mBluetoothAdapter == null) {
finish();
return;
}
}
@Override
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
@Override
protected void onResume() {
super.onResume();
if (!mBluetoothAdapter.isEnabled()) {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
}
// Initializes list view adapter.
mLeDeviceListAdapter = new LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(true);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// User chose not to enable Bluetooth.
if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
protected void onPause() {
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
if (device == null) return;
UUI D deviceUuid = new UUID(device.hashCode(), ((long)device.hashCode() << 32) );
String deviceUUID = deviceUuid.toString();
db.open();
Cursor c;
c=db.getData();
while (c != null && c.moveToNext())
{
if(deviceUUID.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
sname = c.getString(c.getColumnIndex("devicename"));
sLight= c.getString(c.getColumnIndex("light"));
sAlarm= c.getString(c.getColumnIndex("alarm"));
}
else{
}
}
db.close();
Intent intent = new Intent(this, DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, sname);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS,device.getAddress());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_UUID, deviceUUID);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_LIGHT, sLight);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ALARM, sAlarm);
if (mScanning) {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = false;
}
startActivityForResult(intent, 0);
}
private void scanLeDevice(final boolean enable) {
if (enable) {
// Stops scanning after a pre-defined scan period.
mHandler.postDelayed(new Runnable() {
@Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
}, SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
}
// Adapter for holding devices found through scanning.
private class LeDeviceListAdapter extends BaseAdapter {
private ArrayList<BluetoothDevice> mLeDevices;
private LayoutInflater mInflator;
public LeDeviceListAdapter() {
super();
mLeDevices = new ArrayList<BluetoothDevice>();
mInflator = DeviceScanActivity.this.getLayoutInflater();
}
public void addDevice(BluetoothDevice device) {
if(!mLeDevices.contains(device)&& device.getName().startsWith("BRV")) {
mLeDevices.add(device);
}
}
public BluetoothDevice getDevice(int position) {
return mLeDevices.get(position);
}
public void clear() {
mLeDevices.clear();
}
@Override
public int getCount() {
return mLeDevices.size();
}
@Override
public Object getItem(int i) {
return mLeDevices.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
// General ListView optimization code.
if (view == null) {
view = mInflator.inflate(R.layout.listitem_device, null);
viewHolder = new ViewHolder();
viewHolder.deviceAddress = (TextView)
view.findViewById(R.id.device_address);
viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
BluetoothDevice device = mLeDevices.get(i);
String deviceName = device.getName();
UUID deviceUuid = new UUID(device.hashCode(), ((long)device.hashCode() << 32));
String deviceId = deviceUuid.toString();
if (deviceName != null && deviceName.length() > 0){
db.open();
if(db!=null)
{
Cursor c;
c=db.getData();
String selectQuery = "SELECT * FROM DeviceDetails";
c = db.select(selectQuery);
while (c != null && c.moveToNext())
{
if (c.moveToFirst()) {
do {
if(deviceId.equalsIgnoreCase(c.getString(c.getColumnIndex("uuid"))))
{
viewHolder.deviceName.setText(c.getString(c.getColumnIndex("devicename")));
}
} while (c.moveToNext());
}
else {
viewHolder.deviceName.setText("noname");
}
}
}
db.close();
}
else
viewHolder.deviceName.setText("unknown_device");
viewHolder.deviceAddress.setText(device.getAddress());
return view;
}
}
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
try{
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();}
catch(Exception e){
}
}
});
}
};
//Scanning for a particualr UUID
// Device scan callback.
private BluetoothAdapter.LeScanCallback mLeScanCallback_particular =
new BluetoothAdapter.LeScanCallback() {
@Override
public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
runOnUiThread(new Runnable() {
@Override
public void run() {
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
static class ViewHolder {
TextView deviceName;
TextView deviceAddress;
}
从这个类中,当我单击项目时,它会移动到devicecontrol活动,所以它如下所示。当我点击它时应移动到devicecontrol活动,它应该弹出像圆圈这样的小菜单,并显示连接等文本。在连接之后它成功了。
private final ServiceConnection mServiceConnection = new ServiceConnection()
{
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
Log.e(TAG, "Unable to initialize Bluetooth");
finish();
}
// Automatically connects to the device upon successful start-up initialization.
mBluetoothLeService.connect(mDeviceAddress);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
mBluetoothLeService = null;
}
};
private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
mConnected = true;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
} else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
mConnected = false;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
create_alert();
} else if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
Log.e(TAG, "Services Discovered");
check_forservices(mBluetoothLeService.getSupportedGattServices());
} else if (BluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA));
}
}
};
private BluetoothLeService mBluetoothGatt;
private void clearUI() {
mGattServicesList.setAdapter((SimpleExpandableListAdapter) null);
mDataField.setText(R.string.no_data);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gatt_services_characteristics);
........
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG,"In resume");
boolean result = false;
registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
if (mBluetoothLeService != null) {
result = mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG, "Connect request result=" + result);
}
Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
protected void onPause() {
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}
protected void onDestroy() {
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = null;
try{
}catch(Exception e){
e.printStackTrace();
}
}
}
private void updateConnectionState(final int resourceId) {
runOnUiThread(new Runnable() {
@Override
public void run() {
}
});
}
private void displayData(String data) {
Log.d("No serives",data );
if (data != null) {
battery.setText(data);
}
}
//Check for LEUCP servie
private void check_forservices(List<BluetoothGattService> gattServices){
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString =getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<ArrayList<HashMap<String, String>>>();
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<String, String>();
uuid = gattService.getUuid().toString();
Log.d("Service UUID::",uuid);
if(uuid.equalsIgnoreCase(SampleGattAttributes.SIMPLE_KEYS_SERVICE)){
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(LIST_NAME,SampleGattAttributes.lookup(uuid,unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
int charrec=gattCharacteristic.getProperties();
if ((charrec | BluetoothGattCharacteristic.PROPERTY_WRITE) > 0) {
Log.d("characterisitc UUID::",uuid+"....."+SampleGattAttributes.PORT1_CHARACTERSITIC);
if(uuid.equalsIgnoreCase(SampleGattAttributes.PORT1_CHARACTERSITIC.toString())){
check_port_1=1;
if(port1.isChecked())
{
}
}
else if(uuid.equalsIgnoreCase(SampleGattAttributes.PORT2_CHARACTERSITIC.toString())){
check_port_2=1;
if(port1.isChecked())
{
}
}
else if(uuid.equalsIgnoreCase(SampleGattAttributes.FINDME_CHARACTERSITIC.toString())){
find_me=1;
}
}
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
if(uuid.equalsIgnoreCase(SampleGattAttributes.BATTERY_SERVICE)){
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
int charrec=gattCharacteristic.getProperties();
如果(uuid.equalsIgnoreCase(SampleGattAttributes.CLIENT_CHARACTERISTIC_CONFIG_BATTERY)){ Log.d(&#34;匹配电池%&#34;,&#34;&#34;); char_write = UUID; byte [] values = {2,1,0,7,0,0,0};
if ((charrec | BluetoothGattCharacteristic.PROPERTY_READ) > 0) {
if (mNotifyCharacteristic != null) {
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic, false);
mNotifyCharacteristic = null;
}
mBluetoothLeService.readCharacteristic(gattCharacteristic);
}
if ((charrec | BluetoothGattCharacteristic.PROPERTY_NOTIFY) > 0) {
mNotifyCharacteristic = gattCharacteristic;
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic, true);
}
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
DeviceControlActivity.this);
// set title
alertDialogBuilder.setTitle(" Service has charactersitic:"+charrec);
// set dialog message
alertDialogBuilder.setMessage("Click yes to exit!").setCancelable(false).setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int id) {
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
}
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
}
}
// Demonstrates how to iterate through the supported GATT Services/Characteristics.
// In this sample, we populate the data structure that is bound to the ExpandableListView
// on the UI.
private void displayGattServices(List<BluetoothGattService> gattServices) {
if (gattServices == null) return;
String uuid = null;
String unknownServiceString = getResources().getString(R.string.unknown_service);
String unknownCharaString = getResources().getString(R.string.unknown_characteristic);
ArrayList<HashMap<String, String>> gattServiceData = new ArrayList<HashMap<String, String>>();
ArrayList<ArrayList<HashMap<String, String>>> gattCharacteristicData
= new ArrayList<ArrayList<HashMap<String, String>>>();
mGattCharacteristics = new ArrayList<ArrayList<BluetoothGattCharacteristic>>();
// Loops through available GATT Services.
for (BluetoothGattService gattService : gattServices) {
HashMap<String, String> currentServiceData = new HashMap<String, String>();
uuid = gattService.getUuid().toString();
currentServiceData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownServiceString));
currentServiceData.put(LIST_UUID, uuid);
gattServiceData.add(currentServiceData);
ArrayList<HashMap<String, String>> gattCharacteristicGroupData =
new ArrayList<HashMap<String, String>>();
List<BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList<BluetoothGattCharacteristic> charas =
new ArrayList<BluetoothGattCharacteristic>();
// Loops through available Characteristics.
for (BluetoothGattCharacteristic gattCharacteristic : gattCharacteristics) {
charas.add(gattCharacteristic);
HashMap<String, String> currentCharaData = new HashMap<String, String>();
uuid = gattCharacteristic.getUuid().toString();
currentCharaData.put(
LIST_NAME, SampleGattAttributes.lookup(uuid, unknownCharaString));
currentCharaData.put(LIST_UUID, uuid);
gattCharacteristicGroupData.add(currentCharaData);
if(uuid.equals(SampleGattAttributes.BATTERY_SERVICE)){
char_write=uuid;
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
DeviceControlActivity.this);
alertDialogBuilder.setTitle("Battery Service has charactersitic:"+char_write);
alertDialogBuilder
.setMessage("Click yes to exit!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int id) {
DeviceControlActivity.this.finish();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
}
SimpleExpandableListAdapter gattServiceAdapter = new SimpleExpandableListAdapter(
this,
gattServiceData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 },
gattCharacteristicData,
android.R.layout.simple_expandable_list_item_2,
new String[] {LIST_NAME, LIST_UUID},
new int[] { android.R.id.text1, android.R.id.text2 }
);
mGattServicesList.setAdapter(gattServiceAdapter);
}
private static IntentFilter makeGattUpdateIntentFilter() {
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE);
return intentFilter;
}
@Override
public void onContentChanged()
{
super.onContentChanged();
}
protected void onRestart() {
// TODO Auto-generated method stub
super.onRestart();
}
public void create_alert(){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
DeviceControlActivity.this);
// set title
alertDialogBuilder.setTitle("Alert");
// set dialog message
alertDialogBuilder
.setMessage("The connection to device was lost. Please reconnect in the device settings menu.")
.setCancelable(false)
.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,int id) {
finish();
}
}
)
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_connect:
progressDialog = ProgressDialog.show(DeviceControlActivity.this, "", "Connecting...");
new Thread() {
@Override
public void run() {
try{
mBluetoothLeService.connect(mDeviceAddress);
sleep(20000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
progressDialog.dismiss();
}
}.start();
// Toast.makeText(DeviceControlActivity.this,"Connecting...", Toast.LENGTH_LONG).show();
return true;
case R.id.menu_disconnect:
mBluetoothLeService.disconnect();
return true;
case android.R.id.home:
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == 0 && resultCode == RESULT_OK) {
String position = data.getStringExtra("Daddress");
String newName = data.getStringExtra("Dname");
String newlight = data.getStringExtra("Dlight");
String newalarm = data.getStringExtra("Dalarm");
title_text.setText(newName);
mDeviceName=newName;
mDeviceLight=newlight;
mDeviceAlarm = newalarm;
}
if (requestCode == 1 && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}