Android 6.0에서 Android Bluetooth Discovery API가 작동하지 않음

스핑크스 같은

근처에있는 블루투스 장치 등을 검색하는 앱을 만들었습니다. 블루투스 어댑터를 구하고, 닫기 프로세스를 열고, 페어링 된 장치를 구하고, 프로세스를 검색 할 수 있습니다. 모든 것이 정상이지만 검색 프로세스가 제대로 작동하지 않습니다.

5 개의 다른 실제 장치에서 내 앱을 테스트했습니다. 현재 Android 버전에 문제가 있음을 깨달았지만 확실하지 않습니다.

내 앱의 검색 프로세스가 진행 중입니다.

  • Huawei P7-Android 버전 : 4.4.2
  • Sony Xperia Z-Android 버전 : 5.1.1
  • Samsung Galaxy J3-Android 버전 : 5.1.1

내 앱의 검색 프로세스가 작동하지 않습니다.

  • Samsung Galaxy S7-Android 버전 : 6.0.1
  • Samsung Galaxy J7-Android 버전 : 6.0.1

MainActivity.java

package com.sphinxlike.bluetoothexample;

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.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Set;

import static java.lang.System.out;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    /* DECLERATIONS */
    // Button
    Button openBtn = null;                                      // Open button
    Button closeBtn = null;                                     // Close button
    Button listBtn = null;                                      // Paired devices list button
    Button searchBtn = null;                                    // Discovery new devices button

    // Bluetooth
    private BluetoothAdapter mBluetoothAdapter = null;          // Local bluetooth adapter variable
    private static final int REQUEST_ENABLE_BT = 1;             // Bluetooth open intent variable
    String mDeviceName = null;
    String mDeviceAddress = null;
    public static String EXTRA_ADDRESS = "device_address";

    // XML
    TextView tvDeviceName = null;                               // To show local bluetooth device's name
    TextView tvBluetoothState = null;                           // To show bluetooth state
    ListView lvDeviceList = null;                               // To list paired devices or discovered devices

    // Set, List, Array Adapter
    private Set<BluetoothDevice> mPairedDevicesSet = null;      // Paired devices Set
    private Set<BluetoothDevice> mNewDevicesSet = null;         // New devices Set
    ArrayAdapter mPairedDevicesAdapter = null;                  // Paired devices array adapter
    ArrayAdapter mNewDevicesAdapter = null;                     // New devices array adapter
    ArrayList bluetoothDeviceList = null;                       // Listing bluetooth devices
    private ArrayList<BluetoothDevice> btDeviceList = new ArrayList<BluetoothDevice>();

    // Bluetooth State Updater
    private Handler mHandler;                                   // Loop in UI

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initializes UI elements
        tvDeviceName = (TextView)findViewById(R.id.deviceName);
        tvBluetoothState = (TextView)findViewById(R.id.bluetoothState);
        openBtn = (Button)findViewById(R.id.openBluetooth);
        closeBtn = (Button)findViewById(R.id.closeBluetooth);
        listBtn = (Button)findViewById(R.id.listBluetooth);
        searchBtn = (Button)findViewById(R.id.searchBluetooth);
        lvDeviceList = (ListView)findViewById(R.id.deviceList);

        // Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // Button checks
        openBtn.setOnClickListener((View.OnClickListener) this);
        closeBtn.setOnClickListener((View.OnClickListener) this);
        listBtn.setOnClickListener((View.OnClickListener) this);
        searchBtn.setOnClickListener((View.OnClickListener) this);

        // To update bluetooth state text view
        tvBluetoothState.setText(String.valueOf(mBluetoothAdapter.getState()));


        // If the phone does not support bluetooth adapter
        if (mBluetoothAdapter == null) {
            tvBluetoothState.setText("Your phone has not Bluetooth Adapter");
            openBtn.setEnabled(false);
            closeBtn.setEnabled(false);
            listBtn.setEnabled(false);
            searchBtn.setEnabled(false);
        }

        // Updater loop
        mHandler = new Handler();
        mHandler.post(mUpdate);
    }

    // Updater Loop
    private Runnable mUpdate = new Runnable() {
        public void run() {
            getBluetoothState();
            mHandler.postDelayed(this, 500);
        }
    };

    // Button onClick method
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.openBluetooth:
                if (!mBluetoothAdapter.isEnabled()) {
                    Intent bluetoothAcIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(bluetoothAcIntent, REQUEST_ENABLE_BT);
                } else {
                    Toast.makeText(getApplicationContext(), "Bluetooth is already open", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.closeBluetooth:
                if (mBluetoothAdapter.isEnabled()) {
                    mBluetoothAdapter.disable();
                } else {
                    Toast.makeText(getApplicationContext(), "Bluetooth is already close", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.listBluetooth:
                pairedDevicesList();
                break;
            case R.id.searchBluetooth:
                IntentFilter filter = new IntentFilter();

                filter.addAction(BluetoothDevice.ACTION_FOUND);
                filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
                filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);

                registerReceiver(mBroadcastReceiver, filter);
                mBluetoothAdapter.startDiscovery();

                break;
        }
    };

    @Override
    public void onDestroy() {
        unregisterReceiver(mBroadcastReceiver);

        super.onDestroy();
    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // Whenever a remote Bluetooth device is found
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                Toast.makeText(getApplicationContext(), device.getName() + ":" + device.getAddress(), Toast.LENGTH_LONG).show();
//                lvDeviceList.setAdapter(mPairedDevicesAdapter);     // Set list view elements with adapter elements
            }
        }
    };

    // Show bluetooth state on UI
    public void getBluetoothState() {
        tvDeviceName.setText("Device Name: " + mBluetoothAdapter.getName());
        switch(mBluetoothAdapter.getState()) {                                // Set bluetooth state text view
            case 10:    // STATE_OFF
                tvBluetoothState.setText("Bluetooth is closed");
                bluetoothDeviceList = new ArrayList();              // Initialize global array list variable that is declared
                mPairedDevicesAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, bluetoothDeviceList);     // Get array list and use in array adapter
                lvDeviceList.setAdapter(mPairedDevicesAdapter);     // Set list view elements with adapter elements
                break;
            case 11:    // STATE_TURNING_ON
                tvBluetoothState.setText("Bluetooth is opening");
                break;
            case 12:    // STATE_ON
                tvBluetoothState.setText("Bluetooth is opened");
                break;
            case 13:    // STATE_TURNING_OFF
                tvBluetoothState.setText("Bluetooth is closing");
                break;
        }

        // If bluetooth adapter  -> Set buttons
        if (mBluetoothAdapter.isEnabled()) {
            // Enable listing button
            listBtn.setEnabled(true);
            searchBtn.setEnabled(true);
        } else {
            // Disable listing button
            listBtn.setEnabled(false);
            searchBtn.setEnabled(false);
        }
    }

    // Get paired device list and adapt to list view
    public void pairedDevicesList()
    {
        if (!mBluetoothAdapter.isEnabled()) {
            Toast.makeText(getApplicationContext(), "Open the Bluetooth", Toast.LENGTH_SHORT).show();
        } else {
            mPairedDevicesSet = mBluetoothAdapter.getBondedDevices();       // Get paired devices
            bluetoothDeviceList = new ArrayList();                      // Initialize global array list variable that is declared

            if (mPairedDevicesSet.size()>0) {
                for (BluetoothDevice bt : mPairedDevicesSet) {              // for-each loop
                    mDeviceName = bt.getName();
                    mDeviceAddress = bt.getAddress();
                    bluetoothDeviceList.add(mDeviceName + "\n" + mDeviceAddress);              // get the device name and add to array list object
                }
            } else if (mPairedDevicesSet.size()<=0){
                Toast.makeText(getApplicationContext(), "No paired devices", Toast.LENGTH_SHORT).show();
            }
            mPairedDevicesAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, bluetoothDeviceList);     // Get array list and use in array adapter
            lvDeviceList.setAdapter(mPairedDevicesAdapter);     // Set list view elements with adapter elements
        }
    }

}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.sphinxlike.bluetoothexample.MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Device Name"
        android:id="@+id/deviceName"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="20dp">

        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/openBluetooth"
            android:text="B. Open"
            android:textAllCaps="false"
            android:layout_gravity="center"
            android:gravity="center"/>
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/closeBluetooth"
            android:text="B. Close"
            android:textAllCaps="false"
            android:layout_gravity="center"
            android:gravity="center"/>
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/listBluetooth"
            android:text="List Paired"
            android:textAllCaps="false"
            android:layout_gravity="center"
            android:gravity="center"/>
        <Button
            android:layout_width="0dp"
            android:layout_weight="1"
            android:layout_height="wrap_content"
            android:id="@+id/searchBluetooth"
            android:text="Search"
            android:textAllCaps="false"
            android:layout_gravity="center"
            android:gravity="center"/>
    </LinearLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:hint="Bluetooth State"
        android:id="@+id/bluetoothState"
        android:layout_gravity="center"
        android:gravity="center"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/deviceList">

    </ListView>
</LinearLayout>
스핑크스 같은

먼저 @Tomasz Czura에게 감사드립니다. 여러 런타임 권한 요청으로 문제를 해결했습니다. Android 개발자 6.0 변경 사항 페이지 내용 :

블루투스 및 Wi-Fi 검색을 통해 주변 외부 기기의 하드웨어 식별자에 액세스하려면 이제 앱에 ACCESS_FINE_LOCATION 또는 ACCESS_COARSE_LOCATION 권한이 있어야합니다.

그래서 AndroidManifest.XML에 권한을 추가했습니다.

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

그런 다음 내 활동을 다음과 같이 재정렬했습니다.

public class MainActivity extends AppCompatActivity {
...
    int ACTION_REQUEST_MULTIPLE_PERMISSION = 1;  // Any number

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...

        int pCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
        pCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
        pCheck += this.checkSelfPermission("Manifest.permission.BLUETOOTH_ADMIN");
        pCheck += this.checkSelfPermission("Manifest.permission.BLUETOOTH");
        if (pCheck != 0) {
            this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.BLUETOOTH_ADMIN, Manifest.permission.BLUETOOTH}, ACTION_REQUEST_MULTIPLE_PERMISSION);
        }
    }
}

작동했습니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Bluetooth startDiscovery ()가 Android 10에서 작동하지 않습니다.

분류에서Dev

일부 Android 기기에서 Geolocation API가 작동하지 않음

분류에서Dev

Android Bluetooth Discovery는 아무것도 기록하지 않습니다.

분류에서Dev

Android : Android 4.3에서 ContentObserver가 작동하지 않음

분류에서Dev

Android에서 웹 서버가 작동하지 않음

분류에서Dev

Android GPS가 서비스에서 작동하지 않음

분류에서Dev

android.support.graphics.drawable.VectorDrawableCompat가 API 21에서만 작동하지 않음

분류에서Dev

Android에서 NotificationListener가 작동하지 않음

분류에서Dev

Android : FragmentPagerAdapter가 ViewPager 및 재질 TabLayout에서 작동하지 않음

분류에서Dev

Xamarin / Visual Studio Mac에서 Android Emulator가 작동하지 않음

분류에서Dev

react-native-image-picker가 Android 10에서 작동하지 않음

분류에서Dev

Android 기기에서 PlayerPrefs가 작동하지 않음

분류에서Dev

Ionic Android 빌드에서 Socket.io가 작동하지 않음

분류에서Dev

HTML 클리너 + XPath가 Android 앱에서 작동하지 않음

분류에서Dev

CSS 높이 %가 Android 앱 화면에서 작동하지 않음

분류에서Dev

Android 2.2에서 ListView 투명도가 작동하지 않음

분류에서Dev

Android Eclipse에서 타이머가 작동하지 않음

분류에서Dev

Android : 스레드에서 addview가 작동하지 않음 (for while)

분류에서Dev

17.04에서 Android Studio 용 Jayatana가 작동하지 않음

분류에서Dev

Android rawQuery에서 SQLite 쿼리가 작동하지 않음

분류에서Dev

Android 4.4에서 NativeScript가 작동하지 않음

분류에서Dev

Android Gravity Center가 textview에서 작동하지 않음

분류에서Dev

Unity에서 Android 기기 카메라가 작동하지 않음

분류에서Dev

OzekiSDK가 Android에서 작동하지 않음

분류에서Dev

Android ListView 어댑터가 Parse SDK에서 작동하지 않음

분류에서Dev

Android 클라이언트에서 OrderByChild ()가 작동하지 않음

분류에서Dev

LayoutInflater가 Android에서 작동하지 않음

분류에서Dev

Ionic 2 @ ionic / storage가 Android 기기에서 작동하지 않음

분류에서Dev

Lombok val 및 var가 Android에서 작동하지 않음

Related 관련 기사

  1. 1

    Bluetooth startDiscovery ()가 Android 10에서 작동하지 않습니다.

  2. 2

    일부 Android 기기에서 Geolocation API가 작동하지 않음

  3. 3

    Android Bluetooth Discovery는 아무것도 기록하지 않습니다.

  4. 4

    Android : Android 4.3에서 ContentObserver가 작동하지 않음

  5. 5

    Android에서 웹 서버가 작동하지 않음

  6. 6

    Android GPS가 서비스에서 작동하지 않음

  7. 7

    android.support.graphics.drawable.VectorDrawableCompat가 API 21에서만 작동하지 않음

  8. 8

    Android에서 NotificationListener가 작동하지 않음

  9. 9

    Android : FragmentPagerAdapter가 ViewPager 및 재질 TabLayout에서 작동하지 않음

  10. 10

    Xamarin / Visual Studio Mac에서 Android Emulator가 작동하지 않음

  11. 11

    react-native-image-picker가 Android 10에서 작동하지 않음

  12. 12

    Android 기기에서 PlayerPrefs가 작동하지 않음

  13. 13

    Ionic Android 빌드에서 Socket.io가 작동하지 않음

  14. 14

    HTML 클리너 + XPath가 Android 앱에서 작동하지 않음

  15. 15

    CSS 높이 %가 Android 앱 화면에서 작동하지 않음

  16. 16

    Android 2.2에서 ListView 투명도가 작동하지 않음

  17. 17

    Android Eclipse에서 타이머가 작동하지 않음

  18. 18

    Android : 스레드에서 addview가 작동하지 않음 (for while)

  19. 19

    17.04에서 Android Studio 용 Jayatana가 작동하지 않음

  20. 20

    Android rawQuery에서 SQLite 쿼리가 작동하지 않음

  21. 21

    Android 4.4에서 NativeScript가 작동하지 않음

  22. 22

    Android Gravity Center가 textview에서 작동하지 않음

  23. 23

    Unity에서 Android 기기 카메라가 작동하지 않음

  24. 24

    OzekiSDK가 Android에서 작동하지 않음

  25. 25

    Android ListView 어댑터가 Parse SDK에서 작동하지 않음

  26. 26

    Android 클라이언트에서 OrderByChild ()가 작동하지 않음

  27. 27

    LayoutInflater가 Android에서 작동하지 않음

  28. 28

    Ionic 2 @ ionic / storage가 Android 기기에서 작동하지 않음

  29. 29

    Lombok val 및 var가 Android에서 작동하지 않음

뜨겁다태그

보관