android之蓝牙操作(一)

[b]与蓝牙相关的API [/b]

1、BluetoothAdapter
该类的对象代表了本地的蓝牙适配器
2、BluetoothDevice
该类的对象代表了远程的蓝牙适配器

[b]扫描已经配对的蓝牙设备步骤:[/b]

1、获得BluetoothAdapter对象
2、判断当前的设备中是否有蓝牙设备
3、判断当前设备中的蓝牙设备是否已经打开
4、得到所以已经配对的蓝牙设备对象

在AndroidManifedt.xml中声明蓝牙权限

package="test.bluetooth01"
android:versionCode="1"
android:versionName="1.0">



android:label="@string/app_name">











在布局文件中添加一个按钮
main.xml

android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>



MainActivity.java

import java.util.Iterator;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class TestBluetoothActivity extends Activity {
/** Called when the activity is first created. */
private Button button = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

button = (Button)findViewById(R.id.button);
button.setOnClickListener(new ButtonListener());
}
private class ButtonListener implements OnClickListener
{

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//得到BluetoothAdapter对象
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//判断BluetoothAdapter对象是否为空,若为空,则本机上无蓝牙设备
if (bluetoothAdapter != null) {
System.out.println("本机上拥有蓝牙设备");
if (!bluetoothAdapter.enable()) {
//创建一个Intent对象,该对象用来启动另外一个Activity,提示用户启动蓝牙设备
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(intent);
}
//得到所有已经匹配的蓝牙适配器对象
Set device = bluetoothAdapter.getBondedDevices();
if (device.size()>0) {
for (Iterator iterator = device.iterator(); iterator
.hasNext();) {
BluetoothDevice bluetoothDevice = (BluetoothDevice) iterator
.next();
System.out.println(bluetoothDevice.getAddress());
}
}

}
else
{
System.out.println("本机上无蓝牙设备");
}
}

}
}

你可能感兴趣的:(android)