Bluetooth Discovery не работает должным образом - PullRequest
0 голосов
/ 16 мая 2018

Я новичок в Android.Я пытаюсь простое приложение для Android, которое будет: - пользователь нажимает кнопку, чтобы включить BT - пользователь нажимает кнопку, он будет сканировать близлежащие устройства и дать список или попытаться подключиться к определенному устройству (приложение будет использоваться в робототехнике). Кнопка anbleработает нормально и включает Bluetooth, но когда я нажимаю кнопку сканирования, он начинает обнаружение, но обратный вызов не возвращается.Я уже настроил прослушиватель и разместил там несколько журналов, и я ничего не вижу от слушателя (я уверен, что во время тестирования у меня есть обнаруживаемые устройства). Вот код ниже:

    public class MainActivity extends AppCompatActivity {

        private BluetoothAdapter BA;
        private Set<BluetoothDevice> scannedDevices;
        private final static int REQUEST_ENABLE_BT = 1;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.menu_main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();

            //noinspection SimplifiableIfStatement
            if (id == R.id.action_settings) {
                return true;
            }

            return super.onOptionsItemSelected(item);
        }

        @Override
        protected void onDestroy() {
            super.onDestroy();
            BA.cancelDiscovery();
            // Don't forget to unregister the ACTION_FOUND receiver.
            unregisterReceiver(mReceiver);
        }


        private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent)
            {
                Log.i("NKNKNK","onReceive method");
                String action = intent.getAction();
                if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                    // A Bluetooth device was found
                    // Getting device information from the intent
                    BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                    Log.i("NKNKNK","Device found: " + device.getName() + "; MAC " + device.getAddress());
                }
            }
        };

        public void TunrONOnClick(View v)
        {
            // do something when the button is clicked
            Log.i("NKNKNK","TunrON button clicked");
            TextView output = findViewById(R.id.textView);

            BA = BluetoothAdapter.getDefaultAdapter();
            if (BA == null)
            {
                Log.i("NKNKNK","No BT device supported");
                return;
            }
            if (!BA.isEnabled()) {
                // We need to enable the Bluetooth, so we ask the user
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                // REQUEST_ENABLE_BT es un valor entero que vale 1
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
            output.setText(BA.getName());
        }

        public void ScanOnClick(View v)
        {
            Log.i("NKNKNK","SCAN button clicked");

            BA = BluetoothAdapter.getDefaultAdapter();
            if (BA.isEnabled())
            {
                if (BA.isDiscovering()) {
                    BA.cancelDiscovery();
                }
                Log.i("NKNKNK","Starting discovery logged");
                BA.startDiscovery();
            }
        }
    }

и нижежурналы, которые я получаю в Android studio:

    05-16 17:10:16.738 3072-3289/com.example.test D/MALI: eglCreateImageKHR:511: [Crop] 0 0 1856 2048  img[1856 2048] 
    05-16 17:10:16.740 3072-3289/com.example.test D/Surface: Surface::connect(this=0x7f8905f000,api=1)
    05-16 17:10:16.741 3072-3289/com.example.test W/libEGL: [ANDROID_RECORDABLE] format: 1
    05-16 17:10:16.742 3072-3289/com.example.test D/mali_winsys: new_window_surface returns 0x3000
    05-16 17:10:16.758 3072-3072/com.example.test W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
    05-16 17:10:16.788 3072-3289/com.example.test I/PerfService: PerfServiceNative api init
    05-16 17:10:16.795 3072-3289/com.example.test D/OpenGLRenderer: CacheTexture 4 upload: x, y, width height = 0, 0, 105, 164
    05-16 17:10:16.801 3072-3289/com.example.test I/[MALI][Gralloc]: [+]r_hnd(0x7f87705aa0), client(50), share_fd(59)
    05-16 17:10:16.801 3072-3289/com.example.test D/GraphicBuffer: register, handle(0x7f87705aa0) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
    05-16 17:10:16.806 3072-3289/com.example.test D/OpenGLRenderer: ProgramCache save to disk, size = 7
    05-16 17:10:16.815 3072-3289/com.example.test I/[MALI][Gralloc]: [+]r_hnd(0x7f87705a00), client(50), share_fd(62)
    05-16 17:10:16.815 3072-3289/com.example.test D/GraphicBuffer: register, handle(0x7f87705a00) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
    05-16 17:10:16.818 3072-3072/com.example.test V/InputMethodManager: onWindowFocus: null softInputMode=288 first=true flags=#81810100
        START INPUT: com.android.internal.policy.PhoneWindow$DecorView{b390d2e V.E...... R.....ID 0,0-1080,1920} ic=null tba=android.view.inputmethod.EditorInfo@f310fac controlFlags=#104
    05-16 17:10:16.838 3072-3289/com.example.test I/[MALI][Gralloc]: [+]r_hnd(0x7f87705be0), client(50), share_fd(65)
    05-16 17:10:16.838 3072-3289/com.example.test D/GraphicBuffer: register, handle(0x7f87705be0) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
    05-16 17:10:20.866 3072-3289/com.example.test I/[MALI][Gralloc]: [+]r_hnd(0x7f87706040), client(50), share_fd(67)
    05-16 17:10:20.866 3072-3289/com.example.test D/GraphicBuffer: register, handle(0x7f87706040) (w:1080 h:1920 s:1088 f:0x1 u:0x000b00)
    05-16 17:10:20.866 3072-3072/com.example.test D/ActivityThread: holder:android.app.IActivityManager$ContentProviderHolder@540fc0a, holder.provider:android.content.ContentProviderProxy@3328c7b
    **05-16 17:10:20.867 3072-3072/com.example.test I/NKNKNK: TunrON button clicked**
    05-16 17:10:20.870 3072-3072/com.example.test D/BluetoothAdapter: isEnabled
    05-16 17:10:20.870 3072-3072/com.example.test I/Timeline: Timeline: Activity_launch_request time:263559951
    05-16 17:10:20.883 3072-3072/com.example.test D/BluetoothAdapter: getName
    05-16 17:10:20.889 3072-3072/com.example.test D/ActivityThread: ACT-AM_ON_PAUSE_CALLED ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}}
    05-16 17:10:20.890 3072-3289/com.example.test D/OpenGLRenderer: CacheTexture 4 upload: x, y, width height = 28, 0, 120, 187
    05-16 17:10:21.659 3072-3072/com.example.test V/ActivityThread: Finishing stop of ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}}: show=true win=com.android.internal.policy.MiuiPhoneWindow@5537557
    05-16 17:10:23.706 3072-3223/com.example.test D/BluetoothAdapter: onBluetoothServiceUp: android.bluetooth.IBluetooth$Stub$Proxy@a93a844
    05-16 17:10:24.130 3072-3072/com.example.test V/ActivityThread: Performing resume of ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}}
    05-16 17:10:24.131 3072-3072/com.example.test D/ActivityThread: ACT-AM_ON_RESUME_CALLED ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}}
    05-16 17:10:24.131 3072-3072/com.example.test V/ActivityThread: Resume ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}} started activity: false, hideForNow: false, finished: false
        Resuming ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}} with isForward=false
    05-16 17:10:24.132 3072-3072/com.example.test V/PhoneWindow: DecorView setVisiblity: visibility = 0 ,Parent =ViewRoot{c8ed89e com.example.test/com.example.test.MainActivity,ident = 0}, this =com.android.internal.policy.PhoneWindow$DecorView{b390d2e V.E...... R....... 0,0-1080,1920}
    05-16 17:10:24.132 3072-3072/com.example.test V/ActivityThread: Scheduling idle handler for ActivityRecord{4162956 token=android.os.BinderProxy@a3cc6c4 {com.example.test/com.example.test.MainActivity}}
    05-16 17:10:24.141 3072-3072/com.example.test V/InputMethodManager: onWindowFocus: null softInputMode=32 first=false flags=#81810100
        START INPUT: com.android.internal.policy.PhoneWindow$DecorView{b390d2e V.E...... R......D 0,0-1080,1920} ic=null tba=android.view.inputmethod.EditorInfo@5ce2ae controlFlags=#100
    05-16 17:10:28.904 3072-3072/com.example.test D/SettingsInterface:  from settings cache , name = sound_effects_enabled , value = 0
    **05-16 17:10:28.904 3072-3072/com.example.test I/NKNKNK: SCAN button clicked
    05-16 17:10:28.904 3072-3072/com.example.test D/BluetoothAdapter: isEnabled
    05-16 17:10:28.906 3072-3072/com.example.test D/BluetoothAdapter: isDiscovering
    05-16 17:10:28.908 3072-3072/com.example.test D/BluetoothAdapter: 141409244: getState(). Returning 12
    05-16 17:10:28.912 3072-3072/com.example.test I/NKNKNK: Starting discovery logged
    05-16 17:10:28.913 3072-3072/com.example.test D/BluetoothAdapter: startDiscovery
    05-16 17:10:28.914 3072-3072/com.example.test D/BluetoothAdapter: 141409244: getState(). Returning 12**

Редактировать: я использую Redmi Note 4 для запуска приложения Спасибо

1 Ответ

0 голосов
/ 17 мая 2018

Привет, я нашел решение для моей проблемы. Похоже, что с Android 6 нужно спрашивать разрешение, а не просто декларировать их в манифесте. поэтому мне пришлось добавить следующие строки перед включением BT:

    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        Log.i("NKNKNK","Permission is not granted");
        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...