蓝牙 BlueTooth
权限
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<!-- 用于访问GPS定位 -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
打开蓝牙
bt_open.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,200);
startActivity(intent);
}
});
关闭蓝牙
bt_close.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapter.disable();
list.clear();
list2.clear();
myAdapter2.notifyDataSetChanged();
myAdapter.notifyDataSetChanged();
}
});
获得已经配对的设备
bt_sao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
list.addAll(bondedDevices);
myAdapter=new MyBAdapter(list,getActivity());
lvv.setAdapter(myAdapter);
}
});
扫描附近的设备
myReceiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
getActivity(). registerReceiver(myReceiver,intentFilter);
bt_fu.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adapter.startDiscovery();
}
});
adapter.startDiscovery();
@Override
public void onDestroy() {
super.onDestroy();
getActivity().unregisterReceiver(myReceiver);
}
class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice parcelableExtra = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
Log.e("##########",parcelableExtra.getName()+":"+parcelableExtra.getAddress());
list2.add(parcelableExtra);
myAdapter2 = new MyBAdapter(list2,context);
myAdapter2.notifyDataSetChanged();
lvv2.setAdapter(myAdapter2);
lvv2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
list2.get(position).createBond();
}
});
}
}
}
}
其他代码
Button bt_open,bt_close,bt_sao,bt_fu;
ListView lvv,lvv2;
MyReceiver myReceiver;
BluetoothAdapter adapter;
MyBAdapter myAdapter;
MyBAdapter myAdapter2;
public static ArrayList<BluetoothDevice> list=new ArrayList<>();
public static ArrayList<BluetoothDevice> list2=new ArrayList<>();
Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what==100){
int max = (int) msg.obj;
Log.e("max",max+"");
pb2.setMax(max);
Log.e("pbmax",pb2.getMax()+"");
}else if(msg.what==101){
int count = (int) msg.obj;
Log.e("count",count+"");
pb2.setProgress(count);
Log.e("pbprogress",pb2.getProgress()+"");
}else if(msg.what==103){
int max = (int) msg.obj;
Log.e("max",max+"");
pb.setMax(max);
Log.e("pbmax",pb.getMax()+"");
}else if(msg.what==104){
int count = (int) msg.obj;
Log.e("count",count+"");
pb.setProgress(count);
Log.e("pbprogress",pb.getProgress()+"");
}
}
};
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View inflate = inflater.inflate(R.layout.fram2, null);
bt_close=inflate.findViewById(R.id.bt_close);
bt_open=inflate.findViewById(R.id.bt_open);
bt_sao=inflate.findViewById(R.id.bt_sao);
bt_fu=inflate.findViewById(R.id.bt_fu);
lvv=inflate.findViewById(R.id.lvv);
lvv2=inflate.findViewById(R.id.lvv2);
BluetoothManager systemService = (BluetoothManager) getActivity().getSystemService(BLUETOOTH_SERVICE);
adapter = systemService.getAdapter();
return inflate;
}
MyAdapter
public class MyBAdapter extends BaseAdapter {
ArrayList<BluetoothDevice> list;
Context context;
public MyBAdapter(ArrayList<BluetoothDevice> list, Context context) {
this.list = list;
this.context = context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View inflate = View.inflate(context, R.layout.layout2, null);
TextView tv = inflate.findViewById(R.id.tv);
tv.setText(list.get(position).getName());
return inflate;
}
}
判断权限
String[] str=new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
if(Build.VERSION.SDK_INT>=23){
if(ActivityCompat.checkSelfPermission(getActivity(),Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
requestPermissions(str,101);
}
}
BlueToothSocket(客户端)
private UUID uuid = UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
lvv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getActivity(), "1111", Toast.LENGTH_SHORT).show();
BluetoothSocket socket = null;
try {
socket = list.get(position).createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket.connect();
new MyThread2(socket,handler).start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
客户端的thread(线程)
public class MyThread2 extends Thread {
BluetoothSocket socket;
Handler handler;
public MyThread2(BluetoothSocket socket, Handler handler) {
this.socket = socket;
this.handler = handler;
}
@Override
public void run() {
super.run();
OutputStream outputStream = null;
try {
outputStream = socket.getOutputStream();
FileInputStream fileInputStream = new FileInputStream("/sdcard/Movies/jljt.mp4");
File file = new File("/sdcard/Movies/jljt.mp4");
Message obtain = Message.obtain();
obtain.what=103;
obtain.obj=(int)file.length();
handler.sendMessage(obtain);
outputStream.write((file.length()+"").getBytes());
Thread.sleep(500);
int len=0;
byte[] b=new byte[1024];
int count=0;
while ((len=fileInputStream.read(b))!=-1){
outputStream.write(b,0,len);
count+=len;
Message obtain1 = Message.obtain();
obtain1.what=104;
obtain1.obj=count;
handler.sendMessage(obtain1);
}
} catch (IOException e1) {
e1.printStackTrace();
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
}
BlueToothServiceSocket(服务端)
new Thread(new Runnable() {
@Override
public void run() {
try {
BluetoothServerSocket serverSocket = adapter.listenUsingInsecureRfcommWithServiceRecord(adapter.getName(), uuid);
while (true){
BluetoothSocket accept = serverSocket.accept();
new MyThread(accept,getActivity(),handler).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
服务端的thread(线程)
class MyThread extends Thread{
BluetoothSocket accept;
Context context;
Handler handler;
public MyThread(BluetoothSocket accept, Context context, Handler handler) {
this.accept = accept;
this.context = context;
this.handler = handler;
}
@Override
public void run() {
super.run();
StringBuffer stringBuffer=new StringBuffer();
try {
InputStream inputStream = accept.getInputStream();
byte[] b=new byte[1024];
int read = inputStream.read(b);
String string1 = new String(b, 0, read);
int lmax=Integer.parseInt(string1);
Log.e("#######",lmax+"");
Message obtain = Message.obtain();
obtain.what=100;
obtain.obj=lmax;
handler.sendMessage(obtain);
int len=0;
int count=0;
FileOutputStream fileOutputStream = new FileOutputStream("/sdcard/DCIM/a.mp4");
while ((len=inputStream.read(b))!=-1){
fileOutputStream.write(b,0,len);
count+=len;
Log.e("#######",count+"");
if(count==lmax){
break;
}
Message obtain1 = Message.obtain();
obtain1.what=101;
obtain1.obj=count;
handler.sendMessage(obtain1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}