这里是我的代码应用广播接收器无法检测附近可用的蓝牙设备,但手机检测
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.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final BroadcastReceiver mReceiver = new 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);
devices.add(device.getName());
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
mBtAdapter.startDiscovery();
Toast.makeText(MainActivity.this,"Discovering "+devices.size(),Toast.LENGTH_SHORT).show();
ArrayAdapter arrayAdapter=new ArrayAdapter(MainActivity.this,android.R.layout.simple_list_item_1,devices);
listView.setAdapter(arrayAdapter);
}
}
};
ListView listView;
ArrayList<String> devices;
private BluetoothAdapter mBtAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView) findViewById(R.id.listView);
devices=new ArrayList<String>();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(mReceiver, filter);
filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
this.registerReceiver(mReceiver, filter);
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if(!mBtAdapter.isEnabled()){
mBtAdapter.enable();
}
mBtAdapter.startDiscovery();
}
@Override
protected void onDestroy(){
super.onDestroy();
mBtAdapter.cancelDiscovery();
unregisterReceiver(mReceiver);
}
}
问题是,它总是显示发现0作为设备的ArrayList的大小始终为0,但手机检测附近的可用设备如下图所示Screenshot of phone bluetooth settings。我认为我的应用广播接收器不检测蓝牙设备可用,因为我的代码中有错误。请帮助我
您是否试图在API 18+设备上运行此代码? – CzarMatt