【发布时间】:2016-04-02 15:44:26
【问题描述】:
我想使用 Android 蓝牙 API 显示绑定设备列表,但我不知道为什么在我的设备上运行此代码时没有显示 toast?顺便说一句,toast 将包含每个设备的名称。
package com.example.fatma.cst;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Set;
import java.util.Vector;
public class MainActivity extends AppCompatActivity {
TextView txt = null;
private static final int REQUEST_ENABLE_BT = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
final Vector mArrayAdapter = null;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter==null){
Toast t=new Toast(this);
t.setText("Sorry your phone do not support Bluetooth");
t.show();
}
else
{
if (!bluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if(REQUEST_ENABLE_BT!=0) {
/* bluetoothAdapter.startDiscovery();
BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Finding devices
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// Add the name and address to an array adapter to show in a ListView
mArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
}
};*/
//IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
// registerReceiver(mReceiver, filter);
Set<BluetoothDevice> devices;
devices = bluetoothAdapter.getBondedDevices();
for (BluetoothDevice blueDevice : devices) {
Toast.makeText(this, "Device = " + blueDevice.getName(), Toast.LENGTH_SHORT).show();
}
}
}
}
}
【问题讨论】:
-
我认为您的问题实际上是关于为什么 Toast 消息没有在您的设备上显示给您。