第一次写博客,希望通过博客的方式可以帮助那些初学安卓开发的人,如果有不对的地方,也希望大神指教一二!
简单的蓝牙开发至需要两个类就可以了,一个是BlueToothAdapter(本机),BluetoothDevice(扫描的外部蓝牙设备).下面直接贴代码,加备注。这是xml文件
<LinearLayout 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:orientation="vertical" >
<Button
android:id="@+id/scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="扫描蓝牙设备" />
<Button
android:id="@+id/set"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="设置可见性" />
</LinearLayout>
下面是MainActivity.java
package com.example.bluetooth;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
BluetoothAdapter adapter;
private Button scan;
private Button set;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
scan = (Button) this.findViewById(R.id.scan);//扫描蓝牙
set = (Button) this.findViewById(R.id.set); //设置可见性按钮
set.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
300);//设置可见性的持续时间。最长300秒
startActivity(intent);
}
});
adapter = BluetoothAdapter.getDefaultAdapter();
scan.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
adapter.startDiscovery();//开始扫描
}
});
//设置过滤器,只过滤蓝牙设备找到的情况
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
DiscoverReceiver receiver = new DiscoverReceiver(); //广播接收者
registerReceiver(receiver, filter);// 注册广播
}
private class DiscoverReceiver extends BroadcastReceiver {
@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);
System.out.println(device.getAddress());
}
}
}
}
需要添加的权限
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>