GATT सर्वर से कनेक्ट करना

किसी BLE डिवाइस से इंटरैक्ट करने के लिए, सबसे पहले डिवाइस को उससे कनेक्ट किया जाता है. ज़्यादा देखें खास तौर पर, डिवाइस पर GATT सर्वर से कनेक्ट करना. GATT से कनेक्ट करने के लिए एक BLE डिवाइस पर काम करने के लिए, connectGatt() तरीका. इस तरीके में तीन पैरामीटर होते हैं: a Context ऑब्जेक्ट, autoConnect (एक बूलियन यह बताता है कि BLE डिवाइस के साथ अपने-आप कनेक्ट होना है या नहीं उपलब्ध हो जाता है) और BluetoothGattCallback:

Kotlin

var bluetoothGatt: BluetoothGatt? = null
...

bluetoothGatt = device.connectGatt(this, false, gattCallback)

Java

bluetoothGatt = device.connectGatt(this, false, gattCallback);

यह BLE डिवाइस के ज़रिए होस्ट किए गए GATT सर्वर से कनेक्ट करता है. साथ ही, BluetoothGatt इंस्टेंस, जो तो GATT क्लाइंट से जुड़ी कार्रवाइयां करने के लिए, उसका इस्तेमाल किया जा सकता है. कॉलर (Android ऐप्लिकेशन) GATT क्लाइंट है. कॉन्टेंट बनाने BluetoothGattCallback का इस्तेमाल, क्लाइंट को नतीजे देने के लिए किया जाता है, जैसे कि कनेक्शन स्टेटस और GATT क्लाइंट से जुड़ी अन्य कार्रवाइयों के बारे में बताया गया है.

सीमित सेवा सेट अप करें

यहां दिए गए उदाहरण में, BLE ऐप्लिकेशन एक गतिविधि देता है ब्लूटूथ डिवाइसों से कनेक्ट करने के लिए, (DeviceControlActivity), डिवाइस का डेटा दिखाएं, और डिवाइस के साथ काम करने वाली GATT सेवाएं और विशेषताएं दिखानी होंगी. जिस जगह की टीम है उपयोगकर्ता के इनपुट के आधार पर, यह गतिविधि Service का नाम BluetoothLeService है, जो यह BLE API के ज़रिए BLE डिवाइस से इंटरैक्ट करता है. उनसे बातचीत की गई बाउंड सेवा का इस्तेमाल करके परफ़ॉर्म किया गया. इसकी मदद से, BluetoothLeService से कनेक्ट करने के लिए गतिविधि और फ़ंक्शन को कॉल करें डिवाइसों से कनेक्ट करें. BluetoothLeService को Binder को लागू करने की ऐसी प्रोसेस जिससे इन चीज़ों का ऐक्सेस मिलता है गतिविधि के लिए सेवा.

Kotlin

class BluetoothLeService : Service() {

    private val binder = LocalBinder()

    override fun onBind(intent: Intent): IBinder? {
        return binder
    }

    inner class LocalBinder : Binder() {
        fun getService() : BluetoothLeService {
            return this@BluetoothLeService
        }
    }
}

Java

class BluetoothLeService extends Service {

    private Binder binder = new LocalBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    class LocalBinder extends Binder {
        public BluetoothLeService getService() {
            return BluetoothLeService.this;
        }
    }
}

गतिविधि, इसका इस्तेमाल करके सेवा चालू कर सकती है bindService() प्रक्रिया को शुरू करने के लिए Intent पास करना सेवा, ServiceConnection कनेक्शन और डिस्कनेक्शन इवेंट को सुनने के लिए लागू किया जाता है. साथ ही, का इस्तेमाल करें.

Kotlin

class DeviceControlActivity : AppCompatActivity() {

    private var bluetoothService : BluetoothLeService? = null

    // Code to manage Service lifecycle.
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName,
            service: IBinder
        ) {
            bluetoothService = (service as LocalBinder).getService()
            bluetoothService?.let { bluetooth ->
                // call functions on service to check connection and connect to devices
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            bluetoothService = null
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.gatt_services_characteristics)

        val gattServiceIntent = Intent(this, BluetoothLeService::class.java)
        bindService(gattServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
    }
}

Java

class DeviceControlActivity extends AppCompatActivity {

    private BluetoothLeService bluetoothService;

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bluetoothService = ((LocalBinder) service).getService();
            if (bluetoothService != null) {
                // call functions on service to check connection and connect to devices
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bluetoothService = null;
        }
    };

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

        Intent gattServiceIntent = new Intent(this, BluetoothLeService.class);
        bindService(gattServiceIntent, serviceConnection, Context.BIND_AUTO_CREATE);
    }
}

Bluetooth अडैप्टर सेट अप करें

सेवा के लिए बाध्य होने के बाद, उसे BluetoothAdapter. इसे ऐसा होना चाहिए देखें कि डिवाइस पर अडैप्टर उपलब्ध है. सेट अप करने का तरीका जानें ब्लूटूथ पर ज़्यादा जानकारी पाएं BluetoothAdapter. नीचे दिए गए उदाहरण में यह सेटअप कोड initialize() फ़ंक्शन जो सफलता को दर्शाने वाली Boolean वैल्यू दिखाता है.

Kotlin

private const val TAG = "BluetoothLeService"

class BluetoothLeService : Service() {

    private var bluetoothAdapter: BluetoothAdapter? = null

    fun initialize(): Boolean {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter()
        if (bluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.")
            return false
        }
        return true
    }

    ...
}

Java

class BluetoothLeService extends Service {

    public static final String TAG = "BluetoothLeService";

    private BluetoothAdapter bluetoothAdapter;

    public boolean initialize() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter == null) {
            Log.e(TAG, "Unable to obtain a BluetoothAdapter.");
            return false;
        }
        return true;
    }

    ...
}

गतिविधि, इस फ़ंक्शन को अपने ServiceConnection लागू करने के तरीके में कॉल करती है. initialize() फ़ंक्शन से गलत रिटर्न वैल्यू को मैनेज करना का इस्तेमाल करें. आप उपयोगकर्ता को यह बताते हुए गड़बड़ी का मैसेज दिखा सकते हैं कि वर्तमान डिवाइस ब्लूटूथ ऑपरेशन का समर्थन नहीं करता या किसी सुविधा को अक्षम नहीं करता जिनके लिए ब्लूटूथ काम करता है. नीचे दिए गए उदाहरण में, गतिविधि के लिए finish() को कॉल किया गया है उपयोगकर्ता को पिछली स्क्रीन पर वापस भेजें.

Kotlin

class DeviceControlActivity : AppCompatActivity() {

    // Code to manage Service lifecycle.
    private val serviceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(
            componentName: ComponentName,
            service: IBinder
        ) {
            bluetoothService = (service as LocalBinder).getService()
            bluetoothService?.let { bluetooth ->
                if (!bluetooth.initialize()) {
                    Log.e(TAG, "Unable to initialize Bluetooth")
                    finish()
                }
                // perform device connection
            }
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            bluetoothService = null
        }
    }

    ...
}

Java

class DeviceControlsActivity extends AppCompatActivity {

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            bluetoothService = ((LocalBinder) service).getService();
            if (bluetoothService != null) {
                if (!bluetoothService.initialize()) {
                    Log.e(TAG, "Unable to initialize Bluetooth");
                    finish();
                }
                // perform device connection
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            bluetoothService = null;
        }
    };

    ...
}

किसी डिवाइस से कनेक्ट करें

BluetoothLeService इंस्टेंस शुरू होने के बाद, इसे बीएलई से कनेक्ट किया जा सकता है डिवाइस. गतिविधि के लिए सेवा को डिवाइस का पता भेजना ज़रूरी है, ताकि वह ये काम कर सके कनेक्शन शुरू करें. सेवा देने वाली कंपनी पहले कॉल करेगी getRemoteDevice() डिवाइस ऐक्सेस करने के लिए, BluetoothAdapter पर. अगर अडैप्टर को पता नहीं चल पा रहा है उसी पते वाले किसी डिवाइस को getRemoteDevice() IllegalArgumentException.

Kotlin

fun connect(address: String): Boolean {
    bluetoothAdapter?.let { adapter ->
        try {
            val device = adapter.getRemoteDevice(address)
        } catch (exception: IllegalArgumentException) {
            Log.w(TAG, "Device not found with provided address.")
            return false
        }
    // connect to the GATT server on the device
    } ?: run {
        Log.w(TAG, "BluetoothAdapter not initialized")
        return false
    }
}

Java

public boolean connect(final String address) {
    if (bluetoothAdapter == null || address == null) {
        Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
        return false;
    }

    try {
        final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
    } catch (IllegalArgumentException exception) {
        Log.w(TAG, "Device not found with provided address.");
        return false;
    }
    // connect to the GATT server on the device
}

सेवा होने के बाद, DeviceControlActivity इस connect() फ़ंक्शन को कॉल करता है शुरू किया गया. गतिविधि को BLE डिवाइस के पते में पास करना ज़रूरी है. तय सीमा में नीचे दिए गए उदाहरण में, डिवाइस का पता गतिविधि को इंटेंट के तौर पर पास किया जाता है अतिरिक्त.

Kotlin

// Code to manage Service lifecycle.
private val serviceConnection: ServiceConnection = object : ServiceConnection {
    override fun onServiceConnected(
    componentName: ComponentName,
    service: IBinder
    ) {
        bluetoothService = (service as LocalBinder).getService()
        bluetoothService?.let { bluetooth ->
            if (!bluetooth.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth")
                finish()
            }
            // perform device connection
            bluetooth.connect(deviceAddress)
        }
    }

    override fun onServiceDisconnected(componentName: ComponentName) {
        bluetoothService = null
    }
}

Java

private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        bluetoothService = ((LocalBinder) service).getService();
        if (bluetoothService != null) {
            if (!bluetoothService.initialize()) {
                Log.e(TAG, "Unable to initialize Bluetooth");
                finish();
            }
            // perform device connection
            bluetoothService.connect(deviceAddress);
        }
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        bluetoothService = null;
    }
};

GATT कॉलबैक का एलान करें

जब गतिविधि के दौरान सेवा को यह बताया जाता है कि उसे किस डिवाइस से कनेक्ट करना है और किस सेवा का इस्तेमाल करना है डिवाइस से कनेक्ट होता है, तो सेवा को BLE डिवाइस. इस कनेक्शन को पाने के लिए, BluetoothGattCallback की ज़रूरत है कनेक्शन की स्थिति, सेवा खोजने की सुविधा, विशेषता के बारे में सूचनाएं पढ़ने, और दिखाने के लिए चुनिंदा सूचनाएं.

इस विषय पर फ़ोकस, कनेक्शन की स्थिति की सूचनाओं पर होता है. BLE ट्रांसफ़र करें' देखें data परफ़ॉर्म करने का तरीका सेवा खोजना, विशेषता रीड करना, और अनुरोध विशेषता नोटिफ़िकेशन.

कॉन्टेंट बनाने onConnectionStateChange() फ़ंक्शन, डिवाइस के GATT सर्वर से कनेक्शन में बदलाव होने पर ट्रिगर होता है. यहां दिए गए उदाहरण में, कॉलबैक को Service क्लास में तय किया गया है, ताकि यह के साथ इस्तेमाल किया जा सकता है BluetoothDevice सेवा से कनेक्ट करती है.

Kotlin

private val bluetoothGattCallback = object : BluetoothGattCallback() {
    override fun onConnectionStateChange(gatt: BluetoothGatt?, status: Int, newState: Int) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // successfully connected to the GATT Server
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // disconnected from the GATT Server
        }
    }
}

Java

private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
    @Override
    public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
        if (newState == BluetoothProfile.STATE_CONNECTED) {
            // successfully connected to the GATT Server
        } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
            // disconnected from the GATT Server
        }
    }
};

GATT सेवा से कनेक्ट करें

BluetoothGattCallback का एलान होने के बाद, सेवा GATT से कनेक्ट करने के लिए, connect() फ़ंक्शन से BluetoothDevice ऑब्जेक्ट एक डिवाइस पर मौजूद सेवाएं.

कॉन्टेंट बनाने connectGatt() फ़ंक्शन का इस्तेमाल किया जाता है. इसके लिए Context ऑब्जेक्ट और autoConnect बूलियन की ज़रूरत है फ़्लैग और BluetoothGattCallback फ़्लैग शामिल कर सकते हैं. इस उदाहरण में, ऐप्लिकेशन सीधे तौर पर BLE डिवाइस से कनेक्ट कर रहा है, ताकि autoConnect के लिए false पास किया जा सके.

BluetoothGatt प्रॉपर्टी भी जोड़ी गई है. ऐसा करने पर, सेवा आपकी साइट की कनेक्शन न होने पर, ज़्यादा समय लग सकता है.

Kotlin

class BluetoothLeService : Service() {

...

    private var bluetoothGatt: BluetoothGatt? = null

    ...

    fun connect(address: String): Boolean {
        bluetoothAdapter?.let { adapter ->
            try {
                val device = adapter.getRemoteDevice(address)
                // connect to the GATT server on the device
                bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback)
                return true
            } catch (exception: IllegalArgumentException) {
                Log.w(TAG, "Device not found with provided address.  Unable to connect.")
                return false
            }
        } ?: run {
            Log.w(TAG, "BluetoothAdapter not initialized")
            return false
        }
    }
}

Java

class BluetoothLeService extends Service {

...

    private BluetoothGatt bluetoothGatt;

    ...

    public boolean connect(final String address) {
        if (bluetoothAdapter == null || address == null) {
            Log.w(TAG, "BluetoothAdapter not initialized or unspecified address.");
            return false;
        }
        try {
            final BluetoothDevice device = bluetoothAdapter.getRemoteDevice(address);
            // connect to the GATT server on the device
            bluetoothGatt = device.connectGatt(this, false, bluetoothGattCallback);
            return true;
        } catch (IllegalArgumentException exception) {
            Log.w(TAG, "Device not found with provided address.  Unable to connect.");
            return false;
        }
    }
}

ब्रॉडकास्ट से जुड़े अपडेट

जब सर्वर GATT सर्वर से कनेक्ट या डिसकनेक्ट होता है, तो उसे सूचित करना होगा नए राज्य की गतिविधि का पता लगा सकते हैं. इसे पूरा करने के कई तरीके हैं. कॉन्टेंट बनाने नीचे दिए गए उदाहरण में ब्रॉडकास्ट का इस्तेमाल किया गया है, ताकि जानकारी सेवा से लेकर गतिविधि तक.

यह सेवा, नई स्थिति को ब्रॉडकास्ट करने के लिए एक फ़ंक्शन का एलान करती है. इस फ़ंक्शन को एक ऐसी कार्रवाई स्ट्रिंग में जिसे ब्रॉडकास्ट किए जाने से पहले किसी Intent ऑब्जेक्ट को पास किया जाता है उसे सिस्टम में जोड़े रखता है.

Kotlin

private fun broadcastUpdate(action: String) {
    val intent = Intent(action)
    sendBroadcast(intent)
}

Java

private void broadcastUpdate(final String action) {
    final Intent intent = new Intent(action);
    sendBroadcast(intent);
}

ब्रॉडकास्ट फ़ंक्शन चालू होने के बाद, उसका इस्तेमाल के साथ कनेक्शन स्थिति के बारे में जानकारी भेजने के लिए BluetoothGattCallback GATT सर्वर. कॉन्सटेंट और सेवा की मौजूदा कनेक्शन स्थिति का एलान किया जाता है Intent कार्रवाइयों को दिखाने वाली सेवा में.

Kotlin

class BluetoothLeService : Service() {

    private var connectionState = STATE_DISCONNECTED

    private val bluetoothGattCallback: BluetoothGattCallback = object : BluetoothGattCallback() {
        override fun onConnectionStateChange(gatt: BluetoothGatt, status: Int, newState: Int) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                connectionState = STATE_CONNECTED
                broadcastUpdate(ACTION_GATT_CONNECTED)
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                connectionState = STATE_DISCONNECTED
                broadcastUpdate(ACTION_GATT_DISCONNECTED)
            }
        }
    }

    ...

    companion object {
        const val ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED"
        const val ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED"

        private const val STATE_DISCONNECTED = 0
        private const val STATE_CONNECTED = 2

    }
}

Java

class BluetoothLeService extends Service {

    public final static String ACTION_GATT_CONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_CONNECTED";
    public final static String ACTION_GATT_DISCONNECTED =
            "com.example.bluetooth.le.ACTION_GATT_DISCONNECTED";

    private static final int STATE_DISCONNECTED = 0;
    private static final int STATE_CONNECTED = 2;

    private int connectionState;
    ...

    private final BluetoothGattCallback bluetoothGattCallback = new BluetoothGattCallback() {
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                // successfully connected to the GATT Server
                connectionState = STATE_CONNECTED;
                broadcastUpdate(ACTION_GATT_CONNECTED);
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                // disconnected from the GATT Server
                connectionState = STATE_DISCONNECTED;
                broadcastUpdate(ACTION_GATT_DISCONNECTED);
            }
        }
    };

    
}

गतिविधि के बारे में अपडेट सुनें

सेवा से कनेक्शन के अपडेट ब्रॉडकास्ट होने के बाद, गतिविधि को BroadcastReceiver लागू करें. गतिविधि सेट अप करते समय इस रिसीवर को रजिस्टर करें और जब गतिविधि, स्क्रीन से बाहर जा रही है. सेवा की मदद से, इवेंट की जानकारी पाकर, यह गतिविधि उपयोगकर्ता इंटरफ़ेस को मौजूदा BLE डिवाइस के साथ कनेक्शन की स्थिति.

Kotlin

class DeviceControlActivity : AppCompatActivity() {

...

    private val gattUpdateReceiver: BroadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                BluetoothLeService.ACTION_GATT_CONNECTED -> {
                    connected = true
                    updateConnectionState(R.string.connected)
                }
                BluetoothLeService.ACTION_GATT_DISCONNECTED -> {
                    connected = false
                    updateConnectionState(R.string.disconnected)
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter())
        if (bluetoothService != null) {
            val result = bluetoothService!!.connect(deviceAddress)
            Log.d(DeviceControlsActivity.TAG, "Connect request result=$result")
        }
    }

    override fun onPause() {
        super.onPause()
        unregisterReceiver(gattUpdateReceiver)
    }

    private fun makeGattUpdateIntentFilter(): IntentFilter? {
        return IntentFilter().apply {
            addAction(BluetoothLeService.ACTION_GATT_CONNECTED)
            addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED)
        }
    }
}

Java

class DeviceControlsActivity extends AppCompatActivity {

...

    private final BroadcastReceiver gattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
                connected = true;
                updateConnectionState(R.string.connected);
            } else if (BluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                connected = false;
                updateConnectionState(R.string.disconnected);
            }
        }
    };

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

        registerReceiver(gattUpdateReceiver, makeGattUpdateIntentFilter());
        if (bluetoothService != null) {
            final boolean result = bluetoothService.connect(deviceAddress);
            Log.d(TAG, "Connect request result=" + result);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(gattUpdateReceiver);
    }

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_DISCONNECTED);
        return intentFilter;
    }
}

BLE डेटा ट्रांसफ़र करें विकल्प में, BroadcastReceiver का इस्तेमाल, सेवा खोजने की जानकारी को इस तरह से बताने के लिए भी किया जाता है साथ ही, इस डिवाइस से मिला खास डेटा.

GATT कनेक्शन बंद करें

ब्लूटूथ कनेक्शन के साथ काम करते समय एक महत्वपूर्ण चरण है ब्लूटूथ कनेक्शन को बंद करना काम पूरा हो जाता है, तो आप उससे कनेक्ट कर सकते हैं. ऐसा करने के लिए, close() पर कॉल करें BluetoothGatt ऑब्जेक्ट पर फ़ंक्शन का इस्तेमाल करें. नीचे दिए गए उदाहरण में, सेवा BluetoothGatt का रेफ़रंस रखता है. जब गतिविधि, बंद कर दिया जाता है, तो डिवाइस की बैटरी तेज़ी से खर्च होने से बचाने के लिए कनेक्शन बंद कर दिया जाता है.

Kotlin

class BluetoothLeService : Service() {

...

    override fun onUnbind(intent: Intent?): Boolean {
        close()
        return super.onUnbind(intent)
    }

    private fun close() {
        bluetoothGatt?.let { gatt ->
            gatt.close()
            bluetoothGatt = null
        }
    }
}

Java

class BluetoothLeService extends Service {

...

      @Override
      public boolean onUnbind(Intent intent) {
          close();
          return super.onUnbind(intent);
      }

      private void close() {
          if (bluetoothGatt == null) {
              Return;
          }
          bluetoothGatt.close();
          bluetoothGatt = null;
      }
}