本文介绍了如何添加小圈连接弹出菜单的时候我就项目点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何添加小圆圈状的弹出菜单时移动到它应该显示连接特定项目后,(像它卷和显示文本连接)/断开(连接时)successfully.now以下是我devicescan activity.in这个我将得到所有BLE设备列表中。这里是我的devicescanactivity
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
getActionBar()的setTitle(BLE设备)。 的UUID =新的UUID [] {(UUID.fromString(0000180f-0000-1000-8000-00805f9b34fb))};
mHandler =新的处理程序();
DB =新DataBaseAdapter(本); //使用这个检查,以确定是否BLE支持设备上。然后你可以
//有选择地禁用BLE相关的功能。
如果(!getPackageManager()。hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(这一点,R.string.ble_not_supported,Toast.LENGTH_SHORT).show();
完();
} //初始化一个蓝牙适配器。对于API 18级以上,获得一个参考
// BluetoothAdapter通过BluetoothManager。
最后BluetoothManager bluetoothManager =
(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter(); //如果蓝牙设备支持的检查。
如果(mBluetoothAdapter == NULL){
完();
返回;
}
}
@覆盖
保护无效onRestart(){
// TODO自动生成方法存根
super.onRestart(); 如果(!mBluetoothAdapter.isEnabled()){
如果(!mBluetoothAdapter.isEnabled()){
意图enableBtIntent =新意图(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
}
//初始化列表视图适配器。
mLeDeviceListAdapter =新LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(真);
}
@覆盖
保护无效onResume(){
super.onResume();
如果(!mBluetoothAdapter.isEnabled()){
如果(!mBluetoothAdapter.isEnabled()){
意图enableBtIntent =新意图(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
} //初始化列表视图适配器。
mLeDeviceListAdapter =新LeDeviceListAdapter();
setListAdapter(mLeDeviceListAdapter);
scanLeDevice(真);
}@覆盖
保护无效的onActivityResult(INT申请code,INT结果code,意图数据){
//用户选择不启用蓝牙。
如果(要求code == REQUEST_ENABLE_BT&放大器;&安培;结果code == Activity.RESULT_CANCELED){
完();
返回;
}
super.onActivityResult(要求code,结果code,数据);
}@覆盖
保护无效的onPause(){
super.onPause();
scanLeDevice(假);
mLeDeviceListAdapter.clear();
}@覆盖
保护无效onListItemClick(ListView中升,视图V,INT位置,长的id){
最后BluetoothDevice类设备= mLeDeviceListAdapter.getDevice(位置); 如果(设备== NULL)回报;
UUIÐdeviceUuid =新的UUID(device.hash code(),((长)device.hash code()<< 32)); 串deviceUUID = deviceUuid.toString(); db.open();
光标C;
C = db.getData(); 而(C =空&安培;!&安培; c.moveToNext())
{
如果(deviceUUID.equalsIgnoreCase(c.getString(c.getColumnIndex(的「uuid)))) {
SNAME = c.getString(c.getColumnIndex(设备名));
轻微= c.getString(c.getColumnIndex(轻));
sAlarm = c.getString(c.getColumnIndex(报警));
}
其他{
}
}
db.close();
意向意图=新意图(这一点,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,轻微的);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ALARM,sAlarm);
如果(mScanning){
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning = FALSE;
}
startActivityForResult(意向,0);
} 私人无效scanLeDevice(最终布尔启用){
如果(启用){
//一个pre定义的扫描时间后停止扫描。
mHandler.postDelayed(新的Runnable(){
@覆盖
公共无效的run(){
mScanning = FALSE;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
},SCAN_PERIOD); mScanning = TRUE;
mBluetoothAdapter.startLeScan(mLeScanCallback); }其他{
mScanning = FALSE;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
} //适配器保持通扫描找到的设备。
私有类LeDeviceListAdapter延伸BaseAdapter {
私人的ArrayList<&BluetoothDevice类GT; mLeDevices;
私人LayoutInflater mInflator; 公共LeDeviceListAdapter(){
超();
mLeDevices =新的ArrayList<&BluetoothDevice类GT;();
mInflator = DeviceScanActivity.this.getLayoutInflater();
} 公共无效的AddDevice(BluetoothDevice类设备){
如果(mLeDevices.contains(设备)及!&安培; device.getName()startsWith(BRV)){
mLeDevices.add(设备);
}
} 公共BluetoothDevice类的getDevice(INT位置){
返回mLeDevices.get(位置);
} 公共无效清除(){
mLeDevices.clear();
} @覆盖
公众诠释的getCount(){
返回mLeDevices.size();
} @覆盖
公共对象的getItem(int i)以{
返回mLeDevices.get(ⅰ);
} @覆盖
众长getItemId(int i)以{
返回我;
} @覆盖
公共查看getView(INT I,观景,ViewGroup中的ViewGroup){
ViewHolder viewHolder;
//一般的ListView优化code。
如果(查看== NULL){
鉴于= mInflator.inflate(R.layout.listitem_device,NULL);
viewHolder =新ViewHolder();
viewHolder.deviceAddress =(TextView中)
view.findViewById(R.id.device_address);
viewHolder.deviceName =(TextView中)view.findViewById(R.id.device_name);
view.setTag(viewHolder);
}其他{
viewHolder =(ViewHolder)view.getTag();
} BluetoothDevice类设备= mLeDevices.get(ⅰ);
字符串DEVICENAME = device.getName();
UUID deviceUuid =新的UUID(device.hash code(),((长)device.hash code()<< 32));
字符串的DeviceID = deviceUuid.toString(); 如果(DEVICENAME =空&放大器;!&放大器; deviceName.length()大于0){
db.open();
如果(DB!= NULL)
{
光标C;
C = db.getData();
字符串selectQuery =SELECT * FROM DeviceDetails
C = db.select(selectQuery);
而(C =空&安培;!&安培; c.moveToNext())
{
如果(c.moveToFirst()){
做{
如果(deviceId.equalsIgnoreCase(c.getString(c.getColumnIndex(的「uuid))))
{
viewHolder.deviceName.setText(c.getString(c.getColumnIndex(设备名)));
} }而(c.moveToNext());
}
其他{
viewHolder.deviceName.setText(NONAME);
}
} } db.close(); }
其他 viewHolder.deviceName.setText(unknown_device);
viewHolder.deviceAddress.setText(device.getAddress()); 返回视图。 }
} //设备扫描回调。
私人BluetoothAdapter.LeScanCallback mLeScanCallback =
新BluetoothAdapter.LeScanCallback(){ @覆盖
公共无效onLeScan(最终BluetoothDevice类设备,INT RSSI,字节[] scanRecord){
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){ 尝试{
mLeDeviceListAdapter.addDevice(设备);
mLeDeviceListAdapter.notifyDataSetChanged();}
赶上(例外五){ }
}
});
}
};
//正在扫描particualr UUID
//设备扫描回调。
私人BluetoothAdapter.LeScanCallback mLeScanCallback_particular =
新BluetoothAdapter.LeScanCallback(){ @覆盖
公共无效onLeScan(最终BluetoothDevice类设备,INT RSSI,字节[] scanRecord){
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
mLeDeviceListAdapter.addDevice(设备);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
静态类ViewHolder {
TextView的DEVICENAME;
TextView的deviceAddress;
}
和从该类当我点击物品将其移动到的DeviceControl活动,以便它是作为follows.when我点击它应该移动到的DeviceControl活动,它应该弹出就像在IT界和显示文本像connecting.and小菜单连接需后,这是成功的。
私人最终ServiceConnection mServiceConnection =新ServiceConnection()
{
@覆盖
公共无效onServiceConnected(组件名组件名,服务的IBinder){
mBluetoothLeService =((BluetoothLeService.LocalBinder)服务).getService();
如果(!mBluetoothLeService.initialize()){
Log.e(TAG,无法初始化蓝牙);
完();
}
//自动连接到在成功启动初始化设备。
mBluetoothLeService.connect(mDeviceAddress);
} @覆盖
公共无效onServiceDisconnected(组件名组件名){
mBluetoothLeService = NULL; }
};
私人最终的BroadcastReceiver mGattUpdateReceiver =新的广播接收器(){
@覆盖
公共无效的onReceive(上下文的背景下,意图意图){
最后弦乐行动= intent.getAction();
如果(BluetoothLeService.ACTION_GATT_CONNECTED.equals(动作)){
mConnected =真;
updateConnectionState(R.string.connected);
invalidateOptionsMenu();
}否则如果(BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(动作)){
mConnected = FALSE;
updateConnectionState(R.string.disconnected);
invalidateOptionsMenu();
create_alert();
}否则如果(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(动作)){
Log.e(TAG,服务发现);
check_forservices(mBluetoothLeService.getSupportedGattServices());
}否则如果(BluetoothLeService.ACTION_DATA_AVAILABLE.equals(动作)){
displayData(intent.getStringExtra(BluetoothLeService.EXTRA_DATA)); }
}
};私人BluetoothLeService mBluetoothGatt; 私人无效clearUI(){
mGattServicesList.setAdapter((SimpleExpandableListAdapter)NULL);
mDataField.setText(R.string.no_data);
}
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
super.onCreate(savedInstanceState);
的setContentView(R.layout.gatt_services_characteristics);
........
}@覆盖
保护无效onResume(){
super.onResume();
Log.d(TAG,在恢复);
布尔结果= FALSE;
registerReceiver(mGattUpdateReceiver,makeGattUpdateIntentFilter());
如果(mBluetoothLeService!= NULL){
结果= mBluetoothLeService.connect(mDeviceAddress);
Log.d(TAG,连接请求结果=+结果);
}
意图gattServiceIntent =新意图(这一点,BluetoothLeService.class);
bindService(gattServiceIntent,mServiceConnection,BIND_AUTO_CREATE); }
保护无效的onPause(){
super.onPause();
unregisterReceiver(mGattUpdateReceiver);
}保护无效的onDestroy(){
super.onDestroy();
unbindService(mServiceConnection);
mBluetoothLeService = NULL;
尝试{
}赶上(例外五){
e.printStackTrace();
} } }
私人无效updateConnectionState(最终诠释RESOURCEID){
runOnUiThread(新的Runnable(){
@覆盖
公共无效的run(){
}
});
}私人无效displayData(字符串数据){
Log.d(否serives数据);
如果(数据!= NULL){
battery.setText(数据);
}
}
//检查LEUCP役 私人无效check_forservices(列表< BluetoothGattService> gattServices){
如果(gattServices == NULL)回报;
字符串UUID = NULL;
。字符串unknownServiceString = getResources()的getString(R.string.unknown_service);
。字符串unknownCharaString = getResources()的getString(R.string.unknown_characteristic);
ArrayList的<&HashMap的LT;字符串,字符串>> gattServiceData =新的ArrayList<&HashMap的LT;字符串,字符串>>();
ArrayList的< ArrayList的<&HashMap的LT;字符串,字符串>>> gattCharacteristicData
=新的ArrayList< ArrayList的<&HashMap的LT;字符串,字符串>>>();
mGattCharacteristics =新的ArrayList< ArrayList的< BluetoothGattCharacteristic>>(); //遍历关贸总协定提供服务。
对于(BluetoothGattService gattService:gattServices){
HashMap的<字符串,字符串> currentServiceData =新的HashMap<字符串,字符串>();
。UUID = gattService.getUuid()的toString();
Log.d(服务UUID ::,UUID); 如果(uuid.equalsIgnoreCase(SampleGattAttributes.SIMPLE_KEYS_SERVICE)){
currentServiceData.put(
LIST_NAME,SampleGattAttributes.lookup(UUID,unknownServiceString));
currentServiceData.put(LIST_UUID,UUID);
gattServiceData.add(currentServiceData); ArrayList的<&HashMap的LT;字符串,字符串>> gattCharacteristicGroupData =
新的ArrayList<&HashMap的LT;字符串,字符串>>();
清单< BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList的< BluetoothGattCharacteristic> charas =
新的ArrayList< BluetoothGattCharacteristic>();
//遍历可用的特点。
对于(BluetoothGattCharacteristic gattCharacteristic:gattCharacteristics){
charas.add(gattCharacteristic);
HashMap的<字符串,字符串> currentCharaData =新的HashMap<字符串,字符串>();
。UUID = gattCharacteristic.getUuid()的toString();
currentCharaData.put(LIST_NAME,SampleGattAttributes.lookup(UUID,unknownCharaString));
currentCharaData.put(LIST_UUID,UUID);
gattCharacteristicGroupData.add(currentCharaData);
INT charrec = gattCharacteristic.getProperties();
如果((charrec | BluetoothGattCharacteristic.PROPERTY_WRITE)大于0){ Log.d(characterisitc UUID ::,UUID +.....+ SampleGattAttributes.PORT1_CHARACTERSITIC);
如果(uuid.equalsIgnoreCase(SampleGattAttributes.PORT1_CHARACTERSITIC.toString())){
check_port_1 = 1; 如果(port1.isChecked())
{
}
}
否则如果(uuid.equalsIgnoreCase(SampleGattAttributes.PORT2_CHARACTERSITIC.toString())){
check_port_2 = 1;
如果(port1.isChecked())
{
}
} 否则如果(uuid.equalsIgnoreCase(SampleGattAttributes.FINDME_CHARACTERSITIC.toString())){ find_me = 1;
}
}
} mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData);
}
如果(uuid.equalsIgnoreCase(SampleGattAttributes.BATTERY_SERVICE)){
currentServiceData.put(
LIST_NAME,SampleGattAttributes.lookup(UUID,unknownServiceString));
currentServiceData.put(LIST_UUID,UUID);
gattServiceData.add(currentServiceData); ArrayList的<&HashMap的LT;字符串,字符串>> gattCharacteristicGroupData =
新的ArrayList<&HashMap的LT;字符串,字符串>>();
清单< BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList的< BluetoothGattCharacteristic> charas =
新的ArrayList< BluetoothGattCharacteristic>(); //遍历可用的特点。
对于(BluetoothGattCharacteristic gattCharacteristic:gattCharacteristics){
charas.add(gattCharacteristic);
HashMap的<字符串,字符串> currentCharaData =新的HashMap<字符串,字符串>();
。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(电池配套%,);
char_write = UUID;
字节[] =值{2,1,0,7,0,0,0};
IF((charrec | BluetoothGattCharacteristic.PROPERTY_READ)0){ 如果(mNotifyCharacteristic!= NULL){
mBluetoothLeService.setCharacteristicNotification(
mNotifyCharacteristic,FALSE);
mNotifyCharacteristic = NULL;
}
mBluetoothLeService.readCharacteristic(gattCharacteristic);
}
如果((charrec | BluetoothGattCharacteristic.PROPERTY_NOTIFY)大于0){
mNotifyCharacteristic = gattCharacteristic;
mBluetoothLeService.setCharacteristicNotification(gattCharacteristic,真);
} AlertDialog.Builder alertDialogBuilder =新AlertDialog.Builder(
DeviceControlActivity.this); //设置标题
alertDialogBuilder.setTitle(服务有charactersitic:+ charrec); //设置对话框消息
alertDialogBuilder.setMessage(单击是退出!)。setCancelable(假).setPositiveButton(是,新DialogInterface.OnClickListener(){
@覆盖
公共无效的onClick(DialogInterface对话,诠释的id){ }
});
//创建警报对话框
AlertDialog alertDialog = alertDialogBuilder.create(); } } mGattCharacteristics.add(charas); gattCharacteristicData.add(gattCharacteristicGroupData);
}
}
}
//演示如何通过所支持的关贸总协定服务/特性迭代。
//在此示例中,我们填充绑定到ExpandableListView的数据结构
//在用户界面上。
私人无效displayGattServices(列表< BluetoothGattService> gattServices){
如果(gattServices == NULL)回报;
字符串UUID = NULL;
。字符串unknownServiceString = getResources()的getString(R.string.unknown_service);
。字符串unknownCharaString = getResources()的getString(R.string.unknown_characteristic);
ArrayList的<&HashMap的LT;字符串,字符串>> gattServiceData =新的ArrayList<&HashMap的LT;字符串,字符串>>();
ArrayList的< ArrayList的<&HashMap的LT;字符串,字符串>>> gattCharacteristicData
=新的ArrayList< ArrayList的<&HashMap的LT;字符串,字符串>>>();
mGattCharacteristics =新的ArrayList< ArrayList的< BluetoothGattCharacteristic>>(); //遍历关贸总协定提供服务。
对于(BluetoothGattService gattService:gattServices){
HashMap的<字符串,字符串> currentServiceData =新的HashMap<字符串,字符串>();
。UUID = gattService.getUuid()的toString(); currentServiceData.put(
LIST_NAME,SampleGattAttributes.lookup(UUID,unknownServiceString));
currentServiceData.put(LIST_UUID,UUID);
gattServiceData.add(currentServiceData); ArrayList的<&HashMap的LT;字符串,字符串>> gattCharacteristicGroupData =
新的ArrayList<&HashMap的LT;字符串,字符串>>();
清单< BluetoothGattCharacteristic> gattCharacteristics =
gattService.getCharacteristics();
ArrayList的< BluetoothGattCharacteristic> charas =
新的ArrayList< BluetoothGattCharacteristic>(); //遍历可用的特点。
对于(BluetoothGattCharacteristic gattCharacteristic:gattCharacteristics){
charas.add(gattCharacteristic);
HashMap的<字符串,字符串> currentCharaData =新的HashMap<字符串,字符串>();
。UUID = gattCharacteristic.getUuid()的toString();
currentCharaData.put(
LIST_NAME,SampleGattAttributes.lookup(UUID,unknownCharaString));
currentCharaData.put(LIST_UUID,UUID);
gattCharacteristicGroupData.add(currentCharaData); 如果(uuid.equals(SampleGattAttributes.BATTERY_SERVICE)){
char_write = UUID;
AlertDialog.Builder alertDialogBuilder =新AlertDialog.Builder(
DeviceControlActivity.this);
alertDialogBuilder.setTitle(电池服务有charactersitic:+ char_write);
alertDialogBuilder
.setMessage(单击是退出!)
.setCancelable(假)
.setPositiveButton(是,新DialogInterface.OnClickListener(){
@覆盖
公共无效的onClick(DialogInterface对话,诠释的id){
DeviceControlActivity.this.finish();
}
});
//创建警报对话框
AlertDialog alertDialog = alertDialogBuilder.create(); // 展示下
alertDialog.show();
} } mGattCharacteristics.add(charas);
gattCharacteristicData.add(gattCharacteristicGroupData);
} SimpleExpandableListAdapter gattServiceAdapter =新SimpleExpandableListAdapter(
这个,
gattServiceData,
android.R.layout.simple_expandable_list_item_2,
新的String [] {LIST_NAME,LIST_UUID},
新的INT [] {android.R.id.text1,android.R.id.text2},
gattCharacteristicData,
android.R.layout.simple_expandable_list_item_2,
新的String [] {LIST_NAME,LIST_UUID},
新的INT [] {android.R.id.text1,android.R.id.text2}
);
mGattServicesList.setAdapter(gattServiceAdapter);
}私有静态的IntentFilter makeGattUpdateIntentFilter(){
最终的IntentFilter的IntentFilter =新的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);
返回IntentFilter的;
}
@覆盖
公共无效onContentChanged()
{
super.onContentChanged(); } 保护无效onRestart(){
// TODO自动生成方法存根 super.onRestart();
}
公共无效create_alert(){ AlertDialog.Builder alertDialogBuilder =新AlertDialog.Builder(
DeviceControlActivity.this); //设置标题
alertDialogBuilder.setTitle(警报); //设置对话框消息
alertDialogBuilder
.setMessage(到设备的连接丢失,请在设备设置菜单中重新连接。)
.setCancelable(假)
.setPositiveButton(OK,新DialogInterface.OnClickListener(){
@覆盖
公共无效的onClick(DialogInterface对话,诠释的id){
完();
}
}
)
.setNegativeButton(取消,新DialogInterface.OnClickListener(){ @覆盖
公共无效的onClick(DialogInterface对话,诠释它){
}
}); AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}@覆盖
公共布尔onOptionsItemSelected(菜单项项){
开关(item.getItemId()){
案例R.id.menu_connect:
progressDialog = ProgressDialog.show(DeviceControlActivity.this,,连接...); 新的Thread(){ @覆盖
公共无效的run(){ 尝试{
mBluetoothLeService.connect(mDeviceAddress);
睡眠(20000); }赶上(例外五){ Log.e(标签,e.getMessage()); } //驳回进度对话框 progressDialog.dismiss(); } }。开始();
// Toast.makeText(DeviceControlActivity.this,连接...,Toast.LENGTH_LONG).show();
返回true;
案例R.id.menu_disconnect:
mBluetoothLeService.disconnect();
返回true;
案例android.R.id.home:
onBack pressed();
返回true; }
返回super.onOptionsItemSelected(项目);
}
公共无效的onActivityResult(INT申请code,INT结果code,意图数据){ 如果(要求code == 0安培;&安培;结果code == RESULT_OK){
字符串位置= data.getStringExtra(Daddress);
串了newName = data.getStringExtra(DNAME);
串newlight = data.getStringExtra(Dlight);
串newalarm = data.getStringExtra(Dalarm); title_text.setText(了newName);
mDeviceName =了newName;
mDeviceLight = newlight;
mDeviceAlarm = newalarm;
} 如果(要求code == 1安培;&安培;结果code == Activity.RESULT_CANCELED){ 完();
返回; }
super.onActivityResult(要求code,结果code,数据);
}
解决方案
看一看 Crouton 。您可以将样式应用于它,即使它一轮弹出文字。
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;
}
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();
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;
}
if (requestCode == 1 && resultCode == Activity.RESULT_CANCELED) {
finish();
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
Have a look at Crouton. You can apply styles to it, i.e. make it round popup with text.
这篇关于如何添加小圈连接弹出菜单的时候我就项目点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!