Coder Social home page Coder Social logo

android-bluetoothlegatt's Introduction

android-bluetoothlegatt's People

Contributors

codingjeremy avatar google-automerger avatar josealcerreca avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

android-bluetoothlegatt's Issues

No connection with Raspberry pi3 board

My Android phone is not connecting with GATT service installed on my Raspberry pi 3 board? No issues but connection state is always "disconnected"
Waiting for your help ASAP

How to make google sample BluetoothLeGatt work in android 6 ?

hello , I am use sample BluetoothLeGatt and it work fine on android 4 , But when I run it on android 6 it not work ( can not find the Bluetooth when it make scan , I search and find the problem because the method stopLeScan and startLeScan are deprecated , I try alot to use the method stopScan and startScan But I can not , so any body can help , this is the hole code of scan :

/*
 * Copyright (C) 2013 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.bluetoothlegatt;

import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

/**
 * Activity for scanning and displaying available Bluetooth LE devices.
 */
public class DeviceScanActivity extends ListActivity {
    private LeDeviceListAdapter mLeDeviceListAdapter;
    private BluetoothAdapter mBluetoothAdapter;
    private boolean mScanning;
    private Handler mHandler;

    private static final int REQUEST_ENABLE_BT = 1;
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle(R.string.title_devices);
        mHandler = new Handler();

        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, R.string.ble_not_supported, Toast.LENGTH_SHORT).show();
            finish();
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, R.string.error_bluetooth_not_supported, Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        if (!mScanning) {
            menu.findItem(R.id.menu_stop).setVisible(false);
            menu.findItem(R.id.menu_scan).setVisible(true);
            menu.findItem(R.id.menu_refresh).setActionView(null);
        } else {
            menu.findItem(R.id.menu_stop).setVisible(true);
            menu.findItem(R.id.menu_scan).setVisible(false);
            menu.findItem(R.id.menu_refresh).setActionView(
                    R.layout.actionbar_indeterminate_progress);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_scan:
                mLeDeviceListAdapter.clear();
                scanLeDevice(true);
                break;
            case R.id.menu_stop:
                scanLeDevice(false);
                break;
        }
        return true;
    }

    @Override
    protected void onResume() {
        super.onResume();

        // Ensures Bluetooth is enabled on the device.  If Bluetooth is not currently enabled,
        // fire an intent to display a dialog asking the user to grant permission to enable it.
        if (!mBluetoothAdapter.isEnabled()) {
            if (!mBluetoothAdapter.isEnabled()) {
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }

        // Initializes list view adapter.
        mLeDeviceListAdapter = new LeDeviceListAdapter();
        setListAdapter(mLeDeviceListAdapter);
        scanLeDevice(true);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            finish();
            return;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onPause() {
        super.onPause();
        scanLeDevice(false);
        mLeDeviceListAdapter.clear();
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        final BluetoothDevice device = mLeDeviceListAdapter.getDevice(position);
        if (device == null) return;
        final Intent intent = new Intent(this, DeviceControlActivity.class);
        intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_NAME, device.getName());
        intent.putExtra(DeviceControlActivity.EXTRAS_DEVICE_ADDRESS, device.getAddress());
        if (mScanning) {
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            mScanning = false;
        }
        startActivity(intent);
    }

    private void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    invalidateOptionsMenu();
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
        }
        invalidateOptionsMenu();
    }

    // Adapter for holding devices found through scanning.
    private class LeDeviceListAdapter extends BaseAdapter {
        private ArrayList<BluetoothDevice> mLeDevices;
        private LayoutInflater mInflator;

        public LeDeviceListAdapter() {
            super();
            mLeDevices = new ArrayList<BluetoothDevice>();
            mInflator = DeviceScanActivity.this.getLayoutInflater();
        }

        public void addDevice(BluetoothDevice device) {
            if(!mLeDevices.contains(device)) {
                mLeDevices.add(device);
            }
        }

        public BluetoothDevice getDevice(int position) {
            return mLeDevices.get(position);
        }

        public void clear() {
            mLeDevices.clear();
        }

        @Override
        public int getCount() {
            return mLeDevices.size();
        }

        @Override
        public Object getItem(int i) {
            return mLeDevices.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            ViewHolder viewHolder;
            // General ListView optimization code.
            if (view == null) {
                view = mInflator.inflate(R.layout.listitem_device, null);
                viewHolder = new ViewHolder();
                viewHolder.deviceAddress = (TextView) view.findViewById(R.id.device_address);
                viewHolder.deviceName = (TextView) view.findViewById(R.id.device_name);
                view.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) view.getTag();
            }

            BluetoothDevice device = mLeDevices.get(i);
            final String deviceName = device.getName();
            if (deviceName != null && deviceName.length() > 0)
                viewHolder.deviceName.setText(deviceName);
            else
                viewHolder.deviceName.setText(R.string.unknown_device);
            viewHolder.deviceAddress.setText(device.getAddress());

            return view;
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback =
            new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mLeDeviceListAdapter.addDevice(device);
                    mLeDeviceListAdapter.notifyDataSetChanged();
                }
            });
        }
    };

    static class ViewHolder {
        TextView deviceName;
        TextView deviceAddress;
    }
}

How to import it into the eclipse?

Hi, I'm new to the BLE and android.Unfortunately, I have got into trouble with importing the project into the eclipse. When I import it as usual, something wrong, there is a red cross under the res folder and no files under the src folder. But I import some similar projects, nothing happened. So what's wrong? Maybe I need to do something special for this project?Thanks a lot.

Application has stopped on nexus 5x (7.1.1)

I built this application and deployed the apk to a nexus 5x with android 7.1.1. The application stops immediately after launching it.

Log:

03-30 10:21:27.570 15188-15188/com.example.android.bluetoothlegatt W/System: ClassLoader referenced unknown path: /data/app/com.example.android.bluetoothlegatt-1/lib/arm64
03-30 10:21:27.581 15188-15188/com.example.android.bluetoothlegatt D/AndroidRuntime: Shutting down VM
03-30 10:21:27.582 15188-15188/com.example.android.bluetoothlegatt E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                     Process: com.example.android.bluetoothlegatt, PID: 15188
                                                                                     java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.android.bluetoothlegatt/com.example.android.bluetoothlegatt.DeviceScanActivity}: java.lang.ClassNotFoundException: Didn't find class "com.example.android.bluetoothlegatt.DeviceScanActivity" on path: DexPathList[[zip file "/data/app/com.example.android.bluetoothlegatt-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.bluetoothlegatt-1/lib/arm64, /system/lib64, /vendor/lib64]]
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2567)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)
                                                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java)
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477)
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                         at android.os.Looper.loop(Looper.java:154)
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                         at java.lang.reflect.Method.invoke(Native Method)
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
                                                                                      Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.android.bluetoothlegatt.DeviceScanActivity" on path: DexPathList[[zip file "/data/app/com.example.android.bluetoothlegatt-1/base.apk"],nativeLibraryDirectories=[/data/app/com.example.android.bluetoothlegatt-1/lib/arm64, /system/lib64, /vendor/lib64]]
                                                                                         at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
                                                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:380)
                                                                                         at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
                                                                                         at android.app.Instrumentation.newActivity(Instrumentation.java:1078)
                                                                                         at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2557)
                                                                                         at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) 
                                                                                         at android.app.ActivityThread.-wrap12(ActivityThread.java) 
                                                                                         at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1477) 
                                                                                         at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                                         at android.os.Looper.loop(Looper.java:154) 
                                                                                         at android.app.ActivityThread.main(ActivityThread.java:6119) 
                                                                                         at java.lang.reflect.Method.invoke(Native Method) 
                                                                                         at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886) 
                                                                                         at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Edit: Solved by changing minimal sdk version to 25. Min version 18 does not work for my device.

Spelling of "Pre-requisites" in README.md

My OCD rebels when I see "Pre-requisites" spelled with a hyphen in huge bold text on the front page of this repository. To make it worse, it's apparently consistent with how it's spelled on most of the other Android sample projects. Ugh!

It's not consistent with how Google otherwise spells "prerequisites", as can be seen by doing the following Google search:

"Pre-requisites" site:http://developer.android.com

See also here: http://www.boards.ie/vbulletin/showthread.php?p=71445610

Scanning on Android 9(Pie) is not working but Scanning on Android 8 is working well

Hi,

I cleared permission issue and compile this source successfully.
When I test this on android 9 on Samsung Note8, this apk couldn't find any ble device.
there is no any error or warning. look below

D/BluetoothAdapter: startLeScan(): null
D/BluetoothAdapter: STATE_ON
I/chatty: uid=10324(com.example.android.bluetoothlegatt) identical 1 line
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Start Scan with callback
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=4 mScannerId=0
D/BluetoothAdapter: stopLeScan()
D/BluetoothAdapter: STATE_ON
D/BluetoothAdapter: STATE_ON
D/BluetoothLeScanner: Stop Scan with callback

But when I test this on android 8 on LG V20, this apk finds all ble devices well.
look below

D/BluetoothAdapter: startLeScan(): null
D/BluetoothAdapter: isLeEnabled(): ON
D/BluetoothLeScanner: onScannerRegistered() - status=0 scannerId=7 mScannerId=0
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@11da351 time:936821296
I/zygote64: Do partial code cache collection, code=17KB, data=24KB
After code cache collection, code=17KB, data=24KB
Increasing code cache capacity to 128KB
I/zygote64: Do partial code cache collection, code=17KB, data=43KB
After code cache collection, code=17KB, data=43KB
Increasing code cache capacity to 256KB
I/zygote64: Compiler allocated 8MB to compile void android.widget.TextView.(android.content.Context, android.util.AttributeSet, int, int)
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@11da351 time:936821296
I/zygote64: Do full code cache collection, code=125KB, data=99KB
I/zygote64: After code cache collection, code=119KB, data=72KB
I/zygote64: Do partial code cache collection, code=124KB, data=88KB
I/zygote64: After code cache collection, code=124KB, data=88KB
Increasing code cache capacity to 512KB
I/zygote64: Compiler allocated 6MB to compile void android.view.ViewRootImpl.performTraversals()
I/zygote64: Do full code cache collection, code=251KB, data=172KB
I/zygote64: After code cache collection, code=206KB, data=131KB
I/zygote64: Do partial code cache collection, code=250KB, data=167KB
I/zygote64: After code cache collection, code=250KB, data=167KB
Increasing code cache capacity to 1024KB
D/BluetoothAdapter: stopLeScan()
D/BluetoothAdapter: isLeEnabled(): ON
D/BluetoothAdapter: stopLeScan()
D/BluetoothAdapter: scan not started yet
<< found all devices >>

I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
I/AudioManagerEx: AudioManagerEx created
D/BluetoothAdapter: stopLeScan()
D/BluetoothAdapter: scan not started yet
D/PhoneWindow: windowLightStatusBar : false, disable View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
I/zygote64: Compiler allocated 8MB to compile void android.widget.TextView.(android.content.Context, android.util.AttributeSet, int, int)
D/BluetoothGatt: connect() - device: 00:50:D4:00:00:20, auto: false
registerApp()
registerApp() - UUID=ab1140bd-a224-4ada-9ace-3780a4567a0c
D/BluetoothLeService: Trying to create a new connection.
D/BluetoothGatt: onClientRegistered() - status=0 clientIf=7
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@89ed9c1 time:936845623
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=7 device=00:50:D4:00:00:20
I/BluetoothLeService: Connected to GATT server.
D/BluetoothGatt: discoverServices() - device: 00:50:D4:00:00:20
I/BluetoothLeService: Attempting to start service discovery:true
D/BluetoothGatt: onConnectionUpdated() - Device=00:50:D4:00:00:20 interval=6 latency=0 timeout=500 status=0
D/BluetoothGatt: onSearchComplete() = Device=00:50:D4:00:00:20 Status=0
D/BluetoothGatt: onConnectionUpdated() - Device=00:50:D4:00:00:20 interval=39 latency=0 timeout=500 status=0
D/BluetoothLeService: Trying to use an existing mBluetoothGatt for connection.
D/DeviceControlActivity: Connect request result=true
I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy@89ed9c1 time:936850696
D/BluetoothGatt: onConnectionUpdated() - Device=00:50:D4:00:00:20 interval=6 latency=0 timeout=500 status=0
D/BluetoothGatt: onConnectionUpdated() - Device=00:50:D4:00:00:20 interval=39 latency=0 timeout=500 status=0
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
D/BluetoothGatt: cancelOpen() - device: 00:50:D4:00:00:20
D/BluetoothGatt: onClientConnectionState() - status=0 clientIf=7 device=00:50:D4:00:00:20
I/BluetoothLeService: Disconnected from GATT server.

BLE scan not working

07-15 23:50:47.130 13302-13302/com.example.android.bluetoothlegatt D/BluetoothAdapter: startLeScan(): null
07-15 23:50:47.132 13302-13302/com.example.android.bluetoothlegatt D/BluetoothAdapter: STATE_ON
07-15 23:50:47.134 13302-13314/com.example.android.bluetoothlegatt D/BluetoothLeScanner: onClientRegistered() - status=0 clientIf=5
07-15 23:50:47.135 13302-13314/com.example.android.bluetoothlegatt W/Binder: Caught a RuntimeException from the binder stub implementation.
java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
at android.os.Parcel.readException(Parcel.java:1599)
at android.os.Parcel.readException(Parcel.java:1552)
at android.bluetooth.IBluetoothGatt$Stub$Proxy.startScan(IBluetoothGatt.java:772)
at android.bluetooth.le.BluetoothLeScanner$BleScanCallbackWrapper.onClientRegistered(BluetoothLeScanner.java:324)
at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:56)
at android.os.Binder.execTransact(Binder.java:453)
07-15 23:50:57.129 13302-13302/com.example.android.bluetoothlegatt D/BluetoothAdapter: stopLeScan()
07-15 23:50:57.131 13302-13302/com.example.android.bluetoothlegatt D/BluetoothAdapter: STATE_ON

no devices detected

Hello,

I imported the Bluetooth Le Gatt project. When I test it on a Samsung tablet, it finds no devices at all and stops scan after the 10 seconds timeout.
On the same tablet there is the BLE Scanner (Bluepixel) application which discovers the BLE devices, so hardware and permissions should be ok....
What can I do to solve this issue?
I found nothing in the log. Location permission is enabled.
I tried #38 but make fails at if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) => error: package Build does not exist

Best regards
Mich

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.