首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >android 2.2和android 6与蓝牙接口的区别

android 2.2和android 6与蓝牙接口的区别
EN

Stack Overflow用户
提问于 2016-08-19 02:35:29
回答 1查看 35关注 0票数 1

我写了一个代码,在蓝牙设备附近扫描API8级,但现在当我要使用同样的API23级应用程序时,它就扫描失败了。除了蓝牙功能之外,其他功能都运行得很好。有人能说出工作哪里出了问题吗?我附上了一个在API8上工作但不能在API23上工作的示例代码

代码语言:javascript
复制
public class MyBluetoothScanActivity extends AppCompatActivity {
Button bt,bt_count;
ListView listView;
BluetoothAdapter btAdapter;
Set<BluetoothDevice> devicesArray;
IntentFilter filter;
BroadcastReceiver receiver;
ArrayAdapter<String> listAdapter;
ArrayList<String> pairedDevices;
ArrayList<BluetoothDevice> devices;
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_bluetooth_scan);

    bt=(Button) findViewById(R.id.bT_scan2);
    bt.setTransformationMethod(null);

    bt_count=(Button) findViewById(R.id.bt_count);
    bt_count.setTransformationMethod(null);

    bt_count.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getBaseContext(),"Count: "+count,Toast.LENGTH_SHORT ).show();
        }
    });




    listView=(ListView) findViewById(R.id.listViewscan);

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);

    if(!btAdapter.isEnabled()){
        turnOnBT();
    }


    init();

    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            newScan();
        }
    });


    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            if(btAdapter.isDiscovering()){
                btAdapter.cancelDiscovery();
            }
            if(!listAdapter.getItem(i).contains("Paired")){
                try {
                    BluetoothDevice selectedDevice = devices.get(i);
                    pairDevice(selectedDevice);
                    Thread.sleep(500);
                    newScan();
                }
                catch (Exception e){}
            }
            else{
                BluetoothDevice selectedDevice = devices.get(i);
                Intent intent=new Intent(getBaseContext(),BtIns.class);
                intent.putExtra("MAC",selectedDevice.getAddress());
                startActivity(intent);
            }
        }
    });
}

private void newScan(){
    btAdapter.cancelDiscovery();
    Toast.makeText(getBaseContext(),"New Scan Start",Toast.LENGTH_SHORT ).show();

    listAdapter= new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,0);
    listView.setAdapter(listAdapter);

    devices = new ArrayList<BluetoothDevice>();
    btAdapter.startDiscovery();
}
private void getPairedDevices() {
    devicesArray = btAdapter.getBondedDevices();
    if(devicesArray.size()>0){
        for(BluetoothDevice device:devicesArray){
            pairedDevices.add(device.getName());

        }
    }
}

void turnOnBT(){
    Intent intent =new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    startActivity(intent);
}

void init(){

    receiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();

            //Toast.makeText(getBaseContext(),"new br: "+action,Toast.LENGTH_LONG ).show();

            if(BluetoothDevice.ACTION_FOUND.equals(action)){

                pairedDevices=new ArrayList<String>();
                getPairedDevices();
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

                //Toast.makeText(getBaseContext(),"Dev: "+device.getName(),Toast.LENGTH_LONG ).show();
                devices.add(device);
                String s = "";
                for(int a = 0; a < pairedDevices.size(); a++){
                    if(device.getName().equals(pairedDevices.get(a))){
                        //append
                        s = "(Paired)";
                        break;
                    }
                }

                listAdapter.add(device.getName()+" "+s+" "+"\n"+device.getAddress());

            }
            else if(BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)){
                if(btAdapter.getState() == btAdapter.STATE_OFF){
                    turnOnBT();
                }
            }


        }
    };
}

private void pairDevice(BluetoothDevice device) {
    try {
        Method m = device.getClass().getMethod("createBond", (Class[]) null);
        m.invoke(device, (Object[]) null);
    } catch (Exception e) {
        Toast.makeText(getBaseContext(),"Exception: "+e.getMessage(),Toast.LENGTH_LONG ).show();
    }
}

@Override
protected void onPause() {
    super.onPause();
    try {
        unregisterReceiver(receiver);
        btAdapter.cancelDiscovery();
    }
    catch (Exception e){}
}


@Override
public void onResume() {
    super.onResume();
    try {
        Toast.makeText(getBaseContext(),"Registration",Toast.LENGTH_SHORT ).show();
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        registerReceiver(receiver, filter);
        filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
        registerReceiver(receiver, filter);
    }
    catch (Exception e){}
}}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-08-19 03:00:03

在API 23和更高版本上扫描蓝牙或Wi-Fi设备需要首先获得Location权限。此外,您还必须确保在设置中启用了位置。

使用谷歌Play服务,你可以检查位置设置,并使用SettingsApi.checkLocationSettings()应用程序接口请求启用它们,例如

代码语言:javascript
复制
final LocationRequest locationRequest = LocationRequest.create();
locationRequest.setPriority(LocationRequest.PRIORITY_LOW_POWER);

final LocationSettingsRequest request = new LocationSettingsRequest.Builder()
        .addLocationRequest(locationRequest)
        .setAlwaysShow(true)
        .setNeedBle(true)
        .build();

mPendingResult = SettingsApi.checkLocationSettings(mClient, request);

请参阅:https://developers.google.com/android/reference/com/google/android/gms/location/SettingsApi

要请求权限,首先需要在清单中声明权限,并在扫描之前请求权限。请参阅此处的文档:https://developer.android.com/training/permissions/requesting.html

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39025269

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档