這裏是我的代碼應用廣播接收器無法檢測附近可用的藍牙設備,但手機檢測
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