package com.example.homework;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.example.homework.adapter.FindBlueToothAdapter;
import com.example.homework.broadcast.MyReceiver;
import com.example.homework.thread.ClientThread;
import com.example.homework.thread.ServerThread;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button mOpen;
private Button mFind;
private Button mClose;
private Button mConnect;
private ListView mFindBlueTooth;
private BluetoothAdapter adapter;
private ListView mConnectedListvew;
private BluetoothDevice bluetoothDevice;
private FindBlueToothAdapter arrayAdapter;
private List<BluetoothDevice> list=new ArrayList<>();
private List<BluetoothDevice> devicesList=new ArrayList<>();
private UUID uuid=UUID.fromString("00001106-0000-1000-8000-00805F9B34FB");
private String[] strings={
Manifest.permission.ACCESS_COARSE_LOCATION ,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH,
Manifest.permission.ACCESS_FINE_LOCATION
};
private Handler handler=new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
if(msg.what==100){
List<BluetoothDevice> lists = (List<BluetoothDevice>) msg.obj;
list=lists;
arrayAdapter.notifyDataSetChanged();
}if(msg.what==110){
String s = (String) msg.obj;
Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
initPermissions();
initReceiver();
initBlueTooth();
initView();
initOnClick();
}
private void initOnClick() {
mFindBlueTooth.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
BluetoothDevice device = list.get(i);
device.createBond();
}
});
mConnectedListvew.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
try {
bluetoothDevice=devicesList.get(i);
BluetoothSocket socket = bluetoothDevice.createInsecureRfcommSocketToServiceRecord(uuid);
new ClientThread(socket,"xyb").start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
private void initPermissions() {
if(Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
requestPermissions(strings,110);
}
}
private void initReceiver() {
MyReceiver myReceiver = new MyReceiver(list,handler);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myReceiver,intentFilter);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode==110&&grantResults[0]== PackageManager.PERMISSION_GRANTED){
}
}
private void initBlueTooth() {
BluetoothManager manager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
adapter = manager.getAdapter();
}
private void initView() {
mOpen = findViewById(R.id.open);
mClose = findViewById(R.id.close);
mFind = findViewById(R.id.find);
mConnect = findViewById(R.id.connect);
mFindBlueTooth = findViewById(R.id.findBlueTooth);
mConnectedListvew = findViewById(R.id.connectedListvew);
}
public void click(View view) {
switch (view.getId()){
case R.id.open:
openBlueTooth();
break;
case R.id.close:
closeBlueTooth();
break;
case R.id.find:
findBlueTooth();
break;
case R.id.connect:
connectBlueTooth();
break;
}
}
private void connectBlueTooth() {
devicesList.clear();
Set<BluetoothDevice> bondedDevices = adapter.getBondedDevices();
devicesList.addAll(bondedDevices);
arrayAdapter=new FindBlueToothAdapter(this,devicesList);
mConnectedListvew.setAdapter(arrayAdapter);
}
private void findBlueTooth() {
list.clear();
arrayAdapter=new FindBlueToothAdapter(this,list);
mFindBlueTooth.setAdapter(arrayAdapter);
adapter.startDiscovery();
}
private void closeBlueTooth() {
adapter.disable();
}
private void openBlueTooth() {
Intent intent = new Intent();
intent.setAction(BluetoothAdapter.ACTION_REQUEST_ENABLE);
intent.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivity(intent);
new Thread(new Runnable() {
@Override
public void run() {
try {
BluetoothServerSocket bluetoothServerSocket = adapter.listenUsingRfcommWithServiceRecord(adapter.getName(), uuid);
BluetoothSocket accept = bluetoothServerSocket.accept();
new ServerThread(accept,handler).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
/**
/外部Broadcast类
获取附近可搜寻蓝牙列表并通过handler回调给activity(方法不唯一)
*/
package com.example.homework.broadcast;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import java.util.List;
public class MyReceiver extends BroadcastReceiver {
private static final String TAG = "MyReceiver";
private List<BluetoothDevice> list;
private Handler handler;
public MyReceiver(List<BluetoothDevice> list,Handler handler) {
this.list = list;
this.handler=handler;
}
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
list.add(device);
Log.i(TAG, "onReceive: "+list.toString());
Message message = new Message();
message.what=100;
message.obj=list;
handler.sendMessage(message);
}else if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
}else if(action.equals(BluetoothAdapter.ACTION_DISCOVERY_FINISHED)){
}
}
}
蓝牙
最新推荐文章于 2023-12-12 14:49:57 发布