我正在尝试编写一个程序,检查某个蓝牙耳机是否会弹出,就像在iPhone上的airpod连接屏幕一样,屏幕上方会显示一个弹出窗口。 现在,我正在努力让手机识别已连接的蓝牙设备。
这是MainActivity.java代码:
package com.example.haylougt1;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
private static Button btnTest;
TextView txtStatus;
TextView txtName;
TextView txtMAC;
private static final int REQUEST_ENABLE_BT = 0;
private static final int REQUEST_DISCOVER_BT = 1;
BluetoothAdapter blueAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// textfield to show status
txtStatus = findViewById(R.id.txtStatus);
txtName = findViewById(R.id.lblName);
txtMAC = findViewById(R.id.lblMAC);
// bluetooth adaptar
blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter == null) {
txtStatus.setText("Bluetooth is not available!");
} else {
txtStatus.setText("Bluetooth is available");
}
btnTest = (Button) findViewById(R.id.btnTest);
btnTest.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> devices = blueAdapter.getBondedDevices();
if (devices.size() > 0) {
for (BluetoothDevice device : devices) {
String deviceName = device.getName();
String deviceMAC = device.getAddress();
txtName.setText(deviceName);
txtMAC.setText(deviceMAC);
}
}
}
}
}
);
}
}
但是,每当我在手机上启动该应用程序时,我唯一得到的就是较早连接但现在未连接的耳塞 You can see that i am not connected to any bluetooth device but still it shows that i am connected