Android-蓝牙Bluetooth

蓝牙设备的搜索-已经细节化,简单易懂。【初始篇】

上代码了:



搜索为匹配蓝牙设备代码:

public class MainActivity extends Activity implements OnBluetoothListener{

	private final static String TAG = MainActivity.class.getSimpleName();
	
	private DeviceListAdapter deviceListAdapter;//listview适配器
	private Builder tipBuilder;
	private ListView listview;
	/*用于搜索蓝牙设备*/
	private BluetoothAdapter localBluetoothAdapter;
	private Handler handler;    
	private ProgressDialog searchDialog;//进度条
	private BluetoothBroadcastReceiver bluetoothBroadcastReceiver;//蓝牙广播
	private Runnable connectRunnable = new Runnable() {
		@Override
		public void run() {
			if(localBluetoothAdapter!=null && localBluetoothAdapter.isEnabled()==true){
				connectBluetooth();
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_ui);
		init();
		running();
		new Handler().post(connectRunnable);
	}
	
	private void init(){
		listview = (ListView) findViewById(R.id.devicelistview);
		deviceListAdapter = new DeviceListAdapter(this);
		listview.setAdapter(deviceListAdapter);
		handler = new Handler();
	}
	/**
	 * 开启蓝牙进行搜索
	 */
	private void running() {
		handler = new Handler();
		localBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		//isOpenBlue();
		localBluetoothAdapter.enable();
		Toast.makeText(getApplicationContext(),
				"蓝牙设备已开启...", Toast.LENGTH_SHORT).show();
	
	}
	
	private void connectBluetooth() {
		searchDialog = new ProgressDialog(this);
		searchDialog.setMessage("正在搜索附近的蓝牙设备...");
		searchDialog.setCancelable(false);
		searchDialog.show();

		IntentFilter intentFilter = new IntentFilter();
		BluetoothBroadcastReceiver.onBluetoothListener = this;
		bluetoothBroadcastReceiver = new BluetoothBroadcastReceiver();
		registerReceiver(bluetoothBroadcastReceiver, intentFilter);
		new Thread() {
			public void run() {
				LogUtil.i(TAG,
						"已经开始搜索");
				localBluetoothAdapter.startDiscovery();
			}
		}.start();
	}
	
	@Override
	public void onSearch(final BluetoothDevice bluetoothdevice) {
		// TODO Auto-generated method stub
		System.out.println(bluetoothdevice.getName());
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (searchDialog != null) {
					searchDialog.dismiss();
					searchDialog = null;
				}
				Toast.makeText(getApplicationContext(), "找到一台蓝牙设备",
						Toast.LENGTH_SHORT).show();
			}
		});
		final Beacon beacon = new Beacon(bluetoothdevice.getName(),bluetoothdevice.getAddress(),
			       "");
		deviceListAdapter.addDevice(beacon);
		deviceListAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void onSearchOver() {
		// TODO Auto-generated method stub
		handler.post(new Runnable() {
			@Override
			public void run() {
				if (searchDialog != null) {
					searchDialog.dismiss();
					Toast.makeText(getApplicationContext(), "搜索完成...没有发现蓝牙设备",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
	}	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		unregisterReceiver(bluetoothBroadcastReceiver);
		super.onDestroy();
	}

}

搜索已配对蓝牙设备代码:


public class ChakanAivity extends Activity {

	private BluetoothAdapter mBluetoothAdapter;
	/* 用于搜索蓝牙设备 */
	private BluetoothAdapter localBluetoothAdapter;
	private Handler handler;
	private ListView listview;
	private DeviceListAdapter deviceListAdapter;// listview适配器

	private BroadcastReceiver mReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub

			String action = intent.getAction();
			// 获得已经搜索到的蓝牙设备
			if (action.equals(BluetoothDevice.ACTION_FOUND)) {
				BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			}
		}
	};

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

		setContentView(R.layout.chakan);
		listview = (ListView) findViewById(R.id.listview);
		deviceListAdapter = new DeviceListAdapter(this);
		listview.setAdapter(deviceListAdapter);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
		// 获取所有已经绑定的蓝牙设备
		Set<BluetoothDevice> devices = mBluetoothAdapter.getBondedDevices();
		if (devices.size() > 0) {
			for (BluetoothDevice bluetoothDevice : devices) {
				Beacon beacon = new Beacon(bluetoothDevice.getName(), bluetoothDevice.getAddress(), "");
				deviceListAdapter.addDevice(beacon);
				deviceListAdapter.notifyDataSetChanged();
			}
		}
	}}

蓝牙广播:

public class BluetoothBroadcastReceiver extends BroadcastReceiver {
	public static final String TAG = "BluetoothBroadcastReceiver";
	public static OnBluetoothListener onBluetoothListener;

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		/**
		 * 找到新的蓝牙设备
		 */
		if (BluetoothDevice.ACTION_FOUND.equals(action)) {
			BluetoothDevice device = intent
					.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			LogUtil.i(TAG,
					"【BluetoothBroadcastReceiver.onReceive()】  info=发现蓝牙设备");
			BluetoothBroadcastReceiver.onBluetoothListener.onSearch(device);
			// }
		} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
			LogUtil.i(TAG,
					"【BluetoothBroadcastReceiver.onReceive()】   info=搜索完成");
			BluetoothBroadcastReceiver.onBluetoothListener.onSearchOver();
		}
	}
}

Listview展示的代码:

activity_main_ui.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ListView
        android:id="@+id/devicelistview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>

listitem_device.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="wrap_content">

    <TextView
        android:id="@+id/device_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="name"
        android:textSize="20dp" />

    <TextView
        android:id="@+id/device_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="address"
        android:textSize="10dp" />

    <TextView
        android:id="@+id/device_beacon_uuid"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="uuid"
        android:textSize="12dp" />
</LinearLayout>


实体,适配:


public class Beacon {
	
	public String name;//蓝牙的名字
	public String Uuid;//Uuid
	public String bluetoothAddress;//地址
	
	public Beacon(String name ,String Uuid,String bluetoothAddress)
	{
		this.name = name ;
		this.Uuid = Uuid ;
		this.bluetoothAddress = bluetoothAddress;
	}
}

public class DeviceListAdapter extends BaseAdapter {

	private ArrayList<Beacon> devices;
	private LayoutInflater layoutInflater;
	private Activity context;//获取上下文

	public DeviceListAdapter(Activity activity) {
		super();
		context = activity;
		devices = new ArrayList<Beacon>();
		layoutInflater = context.getLayoutInflater();
	}

	public void addDevice(Beacon device) {
		if (device == null)
			return;

		for (int i = 0; i < devices.size(); i++) {
			String btAddress = devices.get(i).bluetoothAddress;
			if (btAddress.equals(device.bluetoothAddress)) {
				//若已经存在则不添加直接返回
				devices.add(i,device);
				devices.remove(i);
			}
		}
		devices.add(device);
	}

	public Beacon getDevice(int position) {
		return devices.get(position);
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return devices.size();
	}

	public void clear() {
		devices.clear();
	}

	@Override
	public Object getItem(int i) {
		// TODO Auto-generated method stub
		return devices.get(i);
	}

	@Override
	public long getItemId(int i) {
		// TODO Auto-generated method stub
		return i;
	}

	@Override
	public View getView(int i, View view, ViewGroup viewgroup) {
		// TODO Auto-generated method stub
		ViewHolder viewholder;
		if (view == null) {
			view = layoutInflater.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);
			viewholder.deviceUUID = (TextView) view
					.findViewById(R.id.device_beacon_uuid);

			view.setTag(viewholder);
		} else {
			viewholder = (ViewHolder) view.getTag();
		}
		Beacon device = devices.get(i);
		final String deviceName = device.name;
		if (deviceName != null && deviceName.length() > 0)
			viewholder.deviceName.setText(deviceName);
		else
			viewholder.deviceName.setText("Unknown service");

		viewholder.deviceAddress.setText(device.bluetoothAddress);
		viewholder.deviceUUID.setText(device.Uuid);
		return view;
	}

	class ViewHolder {
		TextView deviceName;
		TextView deviceAddress;
		TextView deviceUUID;
	}
}


AndroidManifest.xml中配置:

	<uses-permission android:name="android.permission.BLUETOOTH"/>  
        <uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>  
	<receiver android:name=".BluetoothBroadcastReceiver" >
            <intent-filter>
                <action android:name="android.bluetooth.device.action.FOUND" />
                <action android:name="android.bluetooth.adapter.action.DISCOVERY_FINISHED" />
            </intent-filter>
        </receiver>



亲写,亲测,木有问题。


     后补实例下载:点击打开链接

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值