Android蓝牙40 ble代码 直接从Eclipse粘贴的代码.docx
《Android蓝牙40 ble代码 直接从Eclipse粘贴的代码.docx》由会员分享,可在线阅读,更多相关《Android蓝牙40 ble代码 直接从Eclipse粘贴的代码.docx(41页珍藏版)》请在冰豆网上搜索。
Android蓝牙40ble代码直接从Eclipse粘贴的代码
程序结合了网上的开源程序。
com.example.android.bluetoothlegatt包中的代码有修改,res文件夹和AndroidManifest.xml中的代码没有修改.
下面直接上代码,并把修改的地方用红色指出来。
/*
*Copyright(C)2013TheAndroidOpenSourceProject
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*http:
//www.apache.org/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/
packagecom.example.android.bluetoothlegatt;
importandroid.app.Activity;
importandroid.app.ListActivity;
importandroid.bluetooth.BluetoothAdapter;
importandroid.bluetooth.BluetoothDevice;
importandroid.bluetooth.BluetoothManager;
importandroid.content.Context;
importandroid.content.Intent;
importandroid.content.pm.PackageManager;
importandroid.os.Bundle;
importandroid.os.Handler;
importandroid.view.LayoutInflater;
importandroid.view.Menu;
importandroid.view.MenuItem;
importandroid.view.View;
importandroid.view.ViewGroup;
importandroid.widget.BaseAdapter;
importandroid.widget.ListView;
importandroid.widget.TextView;
importandroid.widget.Toast;
importjava.util.ArrayList;
/**
*ActivityforscanninganddisplayingavailableBluetoothLEdevices.
*/
publicclassDeviceScanActivityextendsListActivity{
privateLeDeviceListAdaptermLeDeviceListAdapter;//适配器adapter,存放搜寻到的设备信息
privateBluetoothAdaptermBluetoothAdapter;
privatebooleanmScanning;
privateHandlermHandler;
privatestaticfinalintREQUEST_ENABLE_BT=1;
//10秒后停止查找搜索.
privatestaticfinallongSCAN_PERIOD=10000;
@Override
publicvoidonCreate(BundlesavedInstanceState){
super.onCreate(savedInstanceState);
getActionBar().setTitle(R.string.title_devices);//BLEDeviceScan
mHandler=newHandler();
//检查当前手机是否支持ble蓝牙,如果不支持退出程序
if(!
getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(this,R.string.ble_not_supported,Toast.LENGTH_SHORT).show();
finish();
}
//初始化Bluetoothadapter,通过蓝牙管理器得到一个参考蓝牙适配器
//(API必须在以上android4.3或以上和版本)
finalBluetoothManagerbluetoothManager=
(BluetoothManager)getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter=bluetoothManager.getAdapter();
//检查设备上是否支持蓝牙
if(mBluetoothAdapter==null){
Toast.makeText(this,R.string.error_bluetooth_not_supported,Toast.LENGTH_SHORT).show();
finish();
return;
}
}
//选项菜单(optionsMenu)。
在Menu对象的方法来添加菜单或者是子菜单。
@Override
publicbooleanonCreateOptionsMenu(Menumenu){
getMenuInflater().inflate(R.menu.main,menu);
//mScanning代表搜寻与否,初始值为FALSE
if(!
mScanning)
{
menu.findItem(R.id.menu_stop).setVisible(false);
menu.findItem(R.id.menu_scan).setVisible(true);//正在搜索
menu.findItem(R.id.menu_refresh).setActionView(null);
}else{
menu.findItem(R.id.menu_stop).setVisible(true);//停止搜索
menu.findItem(R.id.menu_scan).setVisible(false);
menu.findItem(R.id.menu_refresh).setActionView(
R.layout.actionbar_indeterminate_progress);
}
returntrue;
}
//响应菜单项单击事件,切换搜索与否
@Override
publicbooleanonOptionsItemSelected(MenuItemitem){
switch(item.getItemId()){
caseR.id.menu_scan:
mLeDeviceListAdapter.clear();//清空适配器,重新搜索
scanLeDevice(true);
break;
caseR.id.menu_stop:
scanLeDevice(false);
break;
}
returntrue;
}
//恢复,Activity时候被回调。
@Override
protectedvoidonResume(){
super.onResume();
//为了确保设备上蓝牙能使用,如果当前蓝牙设备没启用,弹出对话框向用户要求授予权限来启用
//EnsuresBluetoothisenabledonthedevice.IfBluetoothisnotcurrentlyenabled,
//fireanintenttodisplayadialogaskingtheusertograntpermissiontoenableit.
if(!
mBluetoothAdapter.isEnabled()){
if(!
mBluetoothAdapter.isEnabled()){
IntentenableBtIntent=newIntent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
}
}
//Initializeslistviewadapter.
mLeDeviceListAdapter=newLeDeviceListAdapter();//新建适配器
setListAdapter(mLeDeviceListAdapter);//数据绑定
scanLeDevice(true);
}
//子activity完成后,需要带回数据给主activity,需要回调该方法
@Override
protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
//UserchosenottoenableBluetooth.
//当运算符两边的表达式的结果都为true时,整个运算结果才为true
if(requestCode==REQUEST_ENABLE_BT&&resultCode==Activity.RESULT_CANCELED){
finish();
return;
}
super.onActivityResult(requestCode,resultCode,data);
}
//暂停activity时候被回调
@Override
protectedvoidonPause(){
super.onPause();
scanLeDevice(false);
mLeDeviceListAdapter.clear();
}
//ListView中的条目短按和长按事件,他们的处理方式是不同的。
对于短按事件,处理起来比较简单,
//我们只需要覆盖ListActivity的onListItemClick()方法
@Override
protectedvoidonListItemClick(ListViewl,Viewv,intposition,longid){
finalBluetoothDevicedevice=mLeDeviceListAdapter.getDevice(position);
if(device==null)return;
finalIntentintent=newIntent(this,DeviceControlActivity.class);
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME,device.getName());
intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS,device.getAddress());
//putExtra("A",B)中,AB为键值对,第一个参数为键名,第二个参数为键对应的值。
//顺便提一下,如果想取出Intent对象中的这些值,需要在你的另一个Activity中用getXXXXXExtra方法,
//注意需要使用对应类型的方法,参数为键名
if(mScanning){
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mScanning=false;
}
startActivity(intent);//启动activity
}
privatevoidscanLeDevice(finalbooleanenable){
if(enable){
//Stopsscanningafterapre-definedscanperiod.
//
mHandler.postDelayed(newRunnable(){
@Override
publicvoidrun(){
mScanning=false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
invalidateOptionsMenu();
}
},SCAN_PERIOD);
mScanning=true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
}else{
mScanning=false;
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
invalidateOptionsMenu();
//在运行时更改选项菜单
//随时动态改变OptionMenu就要实现onPrepareOptionsMenu()方法
}
//继承BaseAdapter,实现adapter,存放listview中的数据。
//实现自己的adapter
//Adapterforholdingdevicesfoundthroughscanning.
privateclassLeDeviceListAdapterextendsBaseAdapter{
privateArrayListmLeDevices;//数组
privateLayoutInflatermInflator;
publicLeDeviceListAdapter()//构造函数
{
super();
mLeDevices=newArrayList();
mInflator=DeviceScanActivity.this.getLayoutInflater();
}
//对象中的方法,addDevice
publicvoidaddDevice(BluetoothDevicedevice)
{
if(!
mLeDevices.contains(device)){
mLeDevices.add(device);
}
}
publicBluetoothDevicegetDevice(intposition){
returnmLeDevices.get(position);
}
publicvoidclear(){
mLeDevices.clear();
}
@Override
publicintgetCount(){
returnmLeDevices.size();
}
@Override
publicObjectgetItem(inti){
returnmLeDevices.get(i);
}
@Override
publiclonggetItemId(inti){
returni;
}
@Override
publicViewgetView(inti,Viewview,ViewGroupviewGroup){
ViewHolderviewHolder;
//GeneralListViewoptimizationcode.
if(view==null){
view=mInflator.inflate(R.layout.listitem_device,null);
viewHolder=newViewHolder();
viewHolder.deviceAddress=(TextView)view.findViewById(R.id.device_address);
viewHolder.deviceName=(TextView)view.findViewById(R.id.device_name);
view.setTag(viewHolder);
//View中的setTag(Onbect)表示给View添加一个格外的数据,以后可以用getTag()将这个数据取出来。
}else{
viewHolder=(ViewHolder)view.getTag();
}
BluetoothDevicedevice=mLeDevices.get(i);
finalStringdeviceName=device.getName();
if(deviceName!
=null&&deviceName.length()>0)
viewHolder.deviceName.setText(deviceName);
else
viewHolder.deviceName.setText(R.string.unknown_device);
viewHolder.deviceAddress.setText(device.getAddress());
returnview;
}
}
//Devicescancallback.
privateBluetoothAdapter.LeScanCallbackmLeScanCallback=
newBluetoothAdapter.LeScanCallback(){
@Override
publicvoidonLeScan(finalBluetoothDevicedevice,intrssi,byte[]scanRecord){
runOnUiThread(newRunnable(){
@Override
publicvoidrun(){
mLeDeviceListAdapter.addDevice(device);
mLeDeviceListAdapter.notifyDataSetChanged();
}
});
}
};
staticclassViewHolder{
TextViewdeviceName;
TextViewdeviceAddress;
}
}
/*
*Copyright(C)2013TheAndroidOpenSourceProject
*
*LicensedundertheApacheLicense,Version2.0(the"License");
*youmaynotusethisfileexceptincompliancewiththeLicense.
*YoumayobtainacopyoftheLicenseat
*
*http:
//www.apache.org/licenses/LICENSE-2.0
*
*Unlessrequiredbyapplicablelaworagreedtoinwriting,software
*distributedundertheLicenseisdistributedonan"ASIS"BASIS,
*WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
*SeetheLicenseforthespecificlanguagegoverningpermissionsand
*limitationsundertheLicense.
*/
packagecom.example.android.bluetoothlegatt;
importjava.util.HashMap;
/**
*ThisclassincludesasmallsubsetofstandardGATTattributesfordemonstrationpurposes.
*/
publicclassSampleGattAttributes{
privatestaticHashMapattributes=newHashMap();
publicstaticStringHEART_RATE_MEASUREMENT="6e400001-b5a3-f393-e0a9-e50e24dcca9e";
publicstaticStringCLIENT_CHARACTERISTIC_CONFIG="00002902-0000-1000-8000-00805f9b34fb";
static{
//SampleServices.
attributes.put("0000180d-0000-1000-8000-00805f9b34fb","HeartRateService");
attributes.put("0000180a-0000-1000-8000-00805f9b34fb","DeviceInformationService");
//SampleCharacteristics.
attributes.put(HEART_RATE_MEASUREMENT,"HeartRateMeasurement");
attributes.put("00002a29-0000-1000-8000-008