আহ, ব্লুটুথ। প্রযুক্তিকে আমরা সবাই ঘৃণা করতে ভালোবাসি। এটা এমন একজন বন্ধুর মতো যে সবসময় সংযোগ করতে চায়, কিন্তু তারপর... করে না।
বছরের পর বছর ধরে, অ্যান্ড্রয়েড বিকাশকারীরা ব্লুটুথের সাথে একটি নাটকীয়, প্রায়শই দুঃখজনক, রোম্যান্সে আটকে আছে। আমরা এর অদ্ভুততার সাথে কুস্তি করেছি, এটিকে শুধু কাজ করার জন্য অনুরোধ করেছি এবং এর রহস্যময় সংযোগের ড্রপগুলির উপর নীরব অশ্রু ঝরিয়েছি৷
কিন্তু যদি আমি আপনাকে বলি যে জিনিসগুলি আরও ভাল হতে চলেছে? যদি আমি আপনাকে বলি যে অ্যান্ড্রয়েড 16 এর সাথে, ব্লুটুথ দেবতারা অবশেষে আমাদের দিকে হাসলেন? এটা স্বপ্ন নয়, বন্ধুরা। এটি AOSP 16 ব্লুটুথ স্ক্যানার, এবং এটি আমাদের ক্লান্ত ডেভেলপারদের জন্য একটি নতুন আশা নিয়ে আসার জন্য।
এই হ্যান্ডবুকে, আমরা একটি যাত্রায় যাচ্ছি। AOSP 16 এর নতুন ব্লুটুথ বৈশিষ্ট্যগুলির হৃদয়ে একটি যাত্রা৷ আমরা হাসব, আমরা কাঁদব (আশা করি এবার আনন্দ থেকে), এবং আমরা শিখব কীভাবে এই নতুন শক্তিগুলিকে ভালোর জন্য ব্যবহার করতে হয়। আমরা প্যাসিভ স্ক্যানিংয়ের জাদু, বন্ড হারানোর কারণের নাটক এবং সাধারণ ঝামেলা ছাড়াই পরিষেবা UUID পাওয়ার নিছক সুবিধার সন্ধান করব।
এই মহাকাব্যের গল্পের শেষে, আপনি সক্ষম হবেন:
-
একটি ব্লুটুথ স্ক্যানার তৈরি করুন যা এত কার্যকর, এটি কার্যত মানসিক৷
-
একজন অভিজ্ঞ গোয়েন্দার মতো সংযোগ সমস্যা ডিবাগ করুন।
-
আপনার নতুন পাওয়া ব্লুটুথ দক্ষতার মাধ্যমে আপনার বন্ধু এবং সহকর্মীদের প্রভাবিত করুন৷
৷
পূর্বশর্ত:
আমরা ডুব দেওয়ার আগে, অ্যান্ড্রয়েড ডেভেলপমেন্ট এবং কোটলিন সম্পর্কে প্রাথমিক ধারণা থাকা ভালো। আপনি যদি কখনও দুটি ডিভাইস একে অপরের সাথে কথা বলার চেষ্টা করে থাকেন এবং আপনার কম্পিউটারকে জানালার বাইরে ফেলে দিতে চান তবে আপনি যোগ্যের চেয়ে বেশি৷
তাই আপনার প্রিয় পানীয় নিন, আপনার কোডিং কেপ পরুন, এবং আসুন ব্লুটুথ জাগরণের জন্য প্রস্তুত হই!
সূচিপত্র
-
অ্যান্ড্রয়েডে ব্লুটুথের সংক্ষিপ্ত ইতিহাস
-
AOSP 16-এ নতুন কি আছে:The Three Musketeers
-
গভীর ডুব #1:প্যাসিভ স্ক্যানিং
-
BluetoothLeScanner বোঝা
-
হ্যান্ডস-অন:আপনার প্রথম প্যাসিভ স্ক্যানার তৈরি করা
-
গভীর ডাইভ #2:ব্লুটুথ বন্ড হারানোর কারণ
-
গভীর ডুব #3:বিজ্ঞাপন থেকে পরিষেবা UUIDs
-
উন্নত বিষয়:আপনার স্ক্যানিং গেমকে সমতল করা
-
বাস্তব-বিশ্ব ব্যবহারের ক্ষেত্রে:যেখানে ব্লুটুথ রাস্তায় আঘাত করে
-
API ভার্সন চেকিং:কিভাবে আপনার অ্যাপ ক্র্যাশ করবেন না
-
টেস্টিং এবং ডিবাগিং:মজার অংশ (সেইড কেউ এভার)
-
কর্মক্ষমতা এবং সর্বোত্তম অভ্যাস:কিভাবে একজন ভালো ব্লুটুথ নাগরিক হতে হয়
-
উপসংহার:ভবিষ্যত প্যাসিভ (এবং এটা ঠিক আছে)
ব্লুটুথের একটি সংক্ষিপ্ত ইতিহাস (বা:কীভাবে আমরা উদ্বেগ বন্ধ করতে শিখেছি এবং রেডিও তরঙ্গকে ভালবাসি)
অন্ধকার যুগ:ক্লাসিক ব্লুটুথ
শুরুতে, ক্লাসিক ব্লুটুথ ছিল। এটি একটি উচ্চস্বরে, উচ্ছ্বসিত পার্টি অতিথির ডিজিটাল সমতুল্য ছিল। এটি অনেক ডেটা বহন করতে পারে (যেমন আপনার প্রিয় টিউনগুলি একটি স্পিকারের সাথে), তবে এটি অবশ্যই একটি ব্যাটারি হগ ছিল। এটা অডিও স্ট্রিমিং জন্য মহান ছিল, কিন্তু ছোট, বিরল তথ্য স্থানান্তর জন্য? এটি একটি বাড়ির গাছপালা জল একটি ফায়ার পায়ের পাতার মোজাবিশেষ ব্যবহার করার মত ছিল. ওভারকিল, এবং সত্যি বলতে, একটু অগোছালো।
এই যুগে বিকাশকারীরা তাদের দিনগুলি ব্লুটুথ অ্যাডাপ্টার, ব্লুটুথ ডিভাইস এবং ভয়ঙ্কর ব্লুটুথ সকেটের সাথে কুস্তি করে কাটিয়েছে। এটি একটি দুর্দান্ত অনিশ্চয়তার সময় ছিল, যেখানে একটি সাধারণ সংযোগ কয়েক সেকেন্ড সময় নিতে পারে, বা... আচ্ছা, আসুন শুধু বলি আপনি এক কাপ কফি বানাতে পারেন৷ আর ব্যাটারি ড্রেন? আপনার ব্যবহারকারীরা তাদের ফোনের পাওয়ার লেভেল সীসা বেলুনের চেয়ে দ্রুত কমতে দেখবে।
The Renaissance:Enter Bluetooth Low Energy (BLE)
তারপরে, অ্যান্ড্রয়েড 4.3 এর সাথে, একটি নতুন নায়ক আবির্ভূত হয়েছিল:ব্লুটুথ লো এনার্জি, বা বিএলই। এটা তোমার বাবার ব্লুটুথ ছিল না। BLE মসৃণ, দক্ষ এবং রহস্যময় ছিল। এটিকে ডেটার সংক্ষিপ্ত বিস্ফোরণের জন্য ডিজাইন করা হয়েছিল, এটি চুগ করার পরিবর্তে একটি সূক্ষ্ম ওয়াইনের মতো শক্তি চুমুক দেয়৷
BLE ব্লকের দুর্দান্ত বাচ্চা ছিল। এটি আমাদের সম্ভাবনার সম্পূর্ণ নতুন জগতের সাথে পরিচয় করিয়ে দিয়েছে:হার্ট-রেট মনিটর, স্মার্ট ঘড়ি এবং এক মিলিয়ন এবং একটি আইওটি ডিভাইস যা একটি একক কয়েন-সেল ব্যাটারিতে কয়েক মাস ধরে চলতে পারে। এটি একটি গেম-চেঞ্জার ছিল৷
কিন্তু মহান শক্তির সাথে এসেছে... বড় জটিলতা। আমাদের GATT, GAP, পরিষেবা এবং বৈশিষ্ট্যগুলির একটি সম্পূর্ণ নতুন ভাষা শিখতে হয়েছিল। এটি সাধারণ স্ক্রিপ্ট লেখা থেকে একটি পূর্ণ-বিকশিত অপেরা রচনা করার মতো ছিল। সম্ভাবনা ছিল বিশাল, কিন্তু শেখার বক্রতা খাড়া ছিল।
সমস্যা শিশু:স্ক্যানিং
এবং তারপর স্ক্যানিং ছিল. এই নতুন, পাওয়ার-সিপিং ডিভাইসগুলি খুঁজে পাওয়ার কাজ। BLE এর প্রথম দিকে, স্ক্যানিং এখনও কিছুটা বন্য পশ্চিমে ছিল। এটি একটি সক্রিয়, গোলমাল প্রক্রিয়া ছিল। আপনার ফোন শূন্যে চিৎকার করবে, "কেউ আছে কি?", এবং তারপর উত্তর শুনুন। এটি কাজ করেছিল, তবে এটি এখনও একটি উল্লেখযোগ্য পাওয়ার ড্রেন ছিল, বিশেষ করে যদি আপনার অ্যাপটিকে দীর্ঘ সময়ের জন্য স্ক্যান করার প্রয়োজন হয়৷
এটি ছিল ক্লাসিক বিকাশকারীর দ্বিধা:আপনাকে ডিভাইসগুলি খুঁজে বের করতে হবে, তবে আপনি লাঞ্চের সময় আপনার ব্যবহারকারীর ফোন মারা যাওয়ার কারণ হতে চান না। বছরের পর বছর ধরে, আমরা ব্যাটারি লাইফের জন্য মরিয়া আবেদনের সাথে আবিষ্কারের প্রয়োজনীয়তার সাথে ভারসাম্য বজায় রেখে এই শক্ত পথ দিয়ে হেঁটেছি।
এটি সেই বিশ্ব যেখানে AOSP 16 এর জন্ম হয়েছিল। একটি বিশ্ব স্ক্যান করার আরও ভাল উপায়ের জন্য চিৎকার করছে৷ একজন নায়কের জন্য প্রস্তুত একটি বিশ্ব। এবং সেই নায়ক, আমার বন্ধুরা, প্যাসিভ স্ক্যানিং। তবে কিছুক্ষণের মধ্যে সে সম্পর্কে আরও...
AOSP 16-এ নতুন কী আছে? (স্পয়লার:এটি আসলে দুর্দান্ত)
ঠিক আছে, চলুন ভাল জিনিস পেতে. AOSP 16 এ অ্যান্ড্রয়েড দল আমাদের কী চকচকে নতুন খেলনা দিয়েছে? দেখা যাচ্ছে, বেশ কয়েকটা! কিন্তু উপহারগুলো খুলে ফেলার আগে, নতুন ডেলিভারির সময়সূচী নিয়ে কথা বলা যাক, কারণ সেটাও এখন একটু ভিন্ন।
এ টেল অফ টু রিলিজ
একটি চমকপ্রদ প্লট টুইস্টে, অ্যান্ড্রয়েড 2025 সালে দুটি বড় এপিআই রিলিজ দিয়ে আমাদের অনুগ্রহ করার সিদ্ধান্ত নিয়েছিল। প্রথমত, আমরা মূল ইভেন্ট পেয়েছি, Android 16 (কোডনাম "বাকলাভা," কারণ একটি ভাল পেস্ট্রি কে পছন্দ করে না?), যেটি Q2 এ এসেছে। এটি আপনার ঐতিহ্যগত, বিগ-ব্যাং রিলিজ যা আপনি জেনেছেন এবং ভালোবাসেন (বা ভয়) সমস্ত আচরণ পরিবর্তনের সাথে।
কিন্তু তারপরে, Q4-এ, আমরা একটি আশ্চর্যজনক দ্বিতীয় কাজ পাই:একটি ছোট রিলিজ, যেখানে আমাদের নতুন ব্লুটুথ গুডিগুলি তাদের দুর্দান্ত প্রবেশদ্বার তৈরি করেছে৷ এই রিলিজটি ভীতিকর, অ্যাপ-ব্রেকিং পরিবর্তন ছাড়াই নতুন বৈশিষ্ট্য এবং API সম্পর্কে। আপনি ইতিমধ্যে বিল পরিশোধ করার পরে এটি একটি বিনামূল্যের ডেজার্ট পাওয়ার মতো।
ব্লুটুথের তিন মাস্কেটিয়ার্স
তাহলে, এই Q4 রিলিজটি ব্লুটুথ পার্টিতে কী নিয়ে এসেছে? আমি খুশি আপনি জিজ্ঞাসা. এটি তিনটি নতুন নায়ক নিয়ে এসেছে, আমাদের ব্লুটুথ সমস্যা থেকে বাঁচাতে প্রস্তুত। আমি তাদের ডাকি... থ্রি মাস্কেটার্স।
বৈশিষ্ট্য
সারাংশ
কেন আপনার যত্ন নেওয়া উচিত
প্যাসিভ স্ক্যানিং
ব্লুটুথ ডিভাইসগুলিকে চিৎকার না করে শোনার ক্ষমতা৷
৷আপনার অ্যাপটি এখন একটি নীরব, ব্যাটারি-সাশ্রয়ী নিনজা হতে পারে৷
৷বন্ড ক্ষতির কারণ
অবশেষে, কেন আপনার ব্লুটুথ সংযোগ বিচ্ছিন্ন হয় সে সম্পর্কে কিছু বন্ধ।
আপনি অনুমান করা গেম খেলা বন্ধ করতে পারেন এবং আসলে সংযোগ সমস্যাগুলি ডিবাগ করতে পারেন৷
৷বিজ্ঞাপন থেকে UUID পরিষেবা
সরাসরি তার বিজ্ঞাপন থেকে একটি ডিভাইসের গুরুত্বপূর্ণ পরিসংখ্যান ধরুন৷
৷এটা ব্লুটুথ ডিভাইসের জন্য গতি ডেটিং মত. দ্রুত, আরও দক্ষ সংযোগ।
এই শুধু ছোটখাট tweaks নয়, লোকেরা. এগুলি হল মানের-জীবনের উন্নতি যা আমরা কীভাবে ব্লুটুথ-সক্ষম অ্যাপগুলি তৈরি এবং ডিবাগ করি তা মৌলিকভাবে পরিবর্তন করবে। মনে হচ্ছে Android টিম আসলে সাহায্যের জন্য আমাদের সম্মিলিত আর্তনাদ শুনেছে। (আমি জানি, আমিও হতবাক।)
পরবর্তী কয়েকটি বিভাগে, আমরা এই নতুন বৈশিষ্ট্যগুলির প্রতিটির সাথে কাছাকাছি এবং ব্যক্তিগতভাবে উঠতে যাচ্ছি। আমরা কোডের মধ্যে ডুব দেব, ব্যবহারের কেসগুলি অন্বেষণ করব এবং কীভাবে তাদের শক্তি ব্যবহার করতে হয় তা শিখব। সুতরাং, আমাদের প্রথম মাস্কেটিয়ারের সাথে দেখা করার জন্য প্রস্তুত হোন:শক্তিশালী, নীরব প্রকার যা প্যাসিভ স্ক্যানিং নামে পরিচিত।
ডিপ ডাইভ #1:প্যাসিভ স্ক্যানিং
কল্পনা করুন আপনি একটি লাইব্রেরিতে আছেন। আপনি একটি বন্ধু খুঁজছেন, কিন্তু তারা কোথায় আপনি জানেন না. আপনার কাছে দুটি বিকল্প আছে:
-
সক্রিয় স্ক্যানিং: আপনি লাইব্রেরির মাঝখানে দাঁড়িয়ে চিৎকার করছেন, "আরে, স্টিভ! তুমি কি এখানে?" এটি কার্যকর, তবে এটি উচ্চস্বরে, বিঘ্নিতও, এবং গ্রন্থাগারিক (যিনি এই উপমায়, আপনার ব্যবহারকারীর ব্যাটারি) দ্বারা আপনাকে বের করে দেবে।
-
প্যাসিভ স্ক্যানিং: আপনি নিঃশব্দে লাইব্রেরির চারপাশে হাঁটছেন, আপনার বন্ধুর স্বাতন্ত্র্যসূচক, হাঁসফাঁস হাসির কথা শুনছেন। তুমি একটা কথাও বলো না। তুমি শুধু শোন। এটি গোপনীয়, দক্ষ এবং আপনার সামাজিক (বা প্রকৃত) ব্যাটারি নিষ্কাশন করবে না।
বছরের পর বছর ধরে, অ্যান্ড্রয়েডের ব্লুটুথ স্ক্যানিং লাইব্রেরিতে চিৎকার করছে। কিন্তু AOSP 16 দিয়ে, আমরা অবশেষে শান্ত শ্রোতা হতে পারি। এটি প্যাসিভ স্ক্যানিংয়ের জাদু।
সক্রিয় বনাম প্যাসিভ:টেকনিক্যাল শোডাউন
BLE এর জগতে, ডিভাইসগুলি "বিজ্ঞাপন" নামে পরিচিত তথ্যের সামান্য প্যাকেট পাঠায়। এটা তাদের বলার উপায়, "আরে, আমি এখানে আছি, এবং আমি এটাই করি!"
-
সক্রিয় স্ক্যানিং: যখন আপনার ফোন একটি সক্রিয় স্ক্যান করে, তখন এটি একটি বিজ্ঞাপন শোনে এবং তারপর একটি SCAN_REQ (স্ক্যান অনুরোধ) ফেরত পাঠায়। এটি মূলত বলছে, "আমাকে আরও বলুন!" পেরিফেরাল ডিভাইসটি তখন একটি SCAN_RSP (স্ক্যান রেসপন্স) দিয়ে উত্তর দেয়, যাতে অতিরিক্ত তথ্য থাকে৷
-
প্যাসিভ স্ক্যানিং: প্যাসিভ স্ক্যানিংয়ের মাধ্যমে, আপনার ফোন বিজ্ঞাপনটি শুনতে পায়... এবং এটাই। এটা কিছু ফেরত পাঠায় না. এটি কেবল প্রাথমিক বিজ্ঞাপনের নোট নেয় এবং এগিয়ে যায়। এটি একটি একমুখী কথোপকথন৷
প্যাসিভ কেন? নীরবতার শক্তি
তাহলে, কেন এই এত বড় চুক্তি? দুটি শব্দ:শক্তি খরচ। প্রতিবার আপনার ফোনের রেডিওকে কিছু (যেমন SCAN_REQ) প্রেরণ করতে হয়, এটি শক্তি ব্যবহার করে। যদি আপনার অ্যাপ সব সময় ডিভাইসের জন্য স্ক্যান করে থাকে, তাহলে সেই সামান্য ট্রান্সমিশনগুলি যোগ হয় এবং আপনার ব্যবহারকারীর ব্যাটারি মূল্য পরিশোধ করে৷
প্যাসিভ স্ক্যানিংয়ে স্যুইচ করে, আপনি রেডিওকে শুধু শুনতে বলছেন। কথা নেই,শুধু শুনছি। এটি স্ক্যান করার জন্য প্রয়োজনীয় শক্তিকে নাটকীয়ভাবে হ্রাস করে, এটিকে দীর্ঘ সময় ধরে কাছাকাছি ডিভাইসগুলির জন্য নিরীক্ষণ করা প্রয়োজন এমন অ্যাপগুলির জন্য একটি নিখুঁত সমাধান করে তোলে৷
কোড:কিভাবে একটি ব্লুটুথ নিনজা হতে হয়
সুতরাং, কিভাবে আমরা এই নতুন স্টিলথ মোড বাস্তবায়ন করব? এটা আশ্চর্যজনক সহজ. আপনি যখন আপনার স্ক্যান শুরু করেন তখন আপনি যে স্ক্যান সেটিংস ব্যবহার করেন তা সবই আসে৷
৷পূর্বে, আপনি এইরকম কিছু করতে পারেন:
val settings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build()
এখন, AOSP 16 এর সাথে, আমাদের কাছে একটি নতুন বিকল্প রয়েছে। প্যাসিভ স্ক্যানিং সক্ষম করতে, আপনি কেবল স্ক্যানের ধরন সেট করুন:
// This is the magic line!
.setScanMode(ScanSettings.SCAN_TYPE_PASSIVE)
দাঁড়াও, এটা ঠিক হতে পারে না। ডকুমেন্টেশন বলছে SCAN_TYPE_PASSIVE একটি স্ক্যান প্রকার, স্ক্যান মোড নয়৷ এবং আপনি ঠিক! আমার ক্ষমাপ্রার্থী, আমি একটু বেশি উত্তেজিত হয়েছি। এটি করার সঠিক উপায় হল স্ক্যান মোডটিকে প্যাসিভ এ সেট করা। এটা আবার চেষ্টা করা যাক.
val settings = ScanSettings.Builder()
// The actual magic line!
.setScanMode(ScanSettings.SCAN_MODE_OPPORTUNISTIC) // This is the closest to passive
.build()
দাঁড়াও, এটাও ঠিক নয়। মনে হচ্ছে আমি আমার তারগুলো পার হয়ে গেছি। আসুন অফিসিয়াল স্ক্রোলগুলি দেখুন... আহ, এখানে! ScanSettings.Builder-এর Android 16 QPR2-এ একটি নতুন পদ্ধতি রয়েছে৷ এটি ScanMode সেট করা নয়, এটি সম্পূর্ণ নতুন সেটিং৷
৷আসুন একবার এবং সব জন্য এই অধিকার পেতে. প্যাসিভ স্ক্যানিং সক্ষম করার সঠিক উপায় এখানে:
// Available in Android 16 QPR2 and later
val settings = ScanSettings.Builder()
// This is the REAL magic line, I promise!
.setScanType(ScanSettings.SCAN_TYPE_PASSIVE)
.build()
এবং সেখানে আপনি এটি আছে. সেই একটি লাইন দিয়ে, আপনি আপনার অ্যাপটিকে একটি উচ্চস্বরে, ব্যাটারি-গজলিং পর্যটক থেকে একটি নীরব, দক্ষ ব্লুটুথ নিনজাতে রূপান্তরিত করেছেন৷ আপনার ব্যবহারকারীদের ব্যাটারি আপনাকে ধন্যবাদ জানাবে৷
অবশ্যই, একটি বাণিজ্য বন্ধ আছে. যেহেতু আপনি একটি SCAN_REQ পাঠাচ্ছেন না, আপনি SCAN_RSP থেকে অতিরিক্ত ডেটা পাবেন না৷ কিন্তু অনেক ব্যবহারের ক্ষেত্রে, প্রাথমিক বিজ্ঞাপনই আপনার প্রয়োজন। এবং শক্তি সঞ্চয় মূল্যের চেয়ে বেশি।
এখন যেহেতু আমরা নীরব স্ক্যানিংয়ের শিল্পে আয়ত্ত করেছি, আসুন ধাঁধার পরবর্তী অংশে চলে যাই:BluetoothLeScanner নিজেই বোঝা।
BluetoothLeScanner (আমাদের অনুষ্ঠানের তারকা) বোঝা
আমরা সত্যিই ব্লুটুথ স্ক্যানিং এর শিল্প আয়ত্ত করতে পারার আগে, আমাদের প্রথমে আমাদের প্রাথমিক অস্ত্র বুঝতে হবে:ব্লুটুথলেস্ক্যানার। এটিকে ঘোস্টবাস্টারের PKE মিটার হিসাবে মনে করুন। এটি এমন একটি টুল যা আমরা আমাদের চারপাশে ভাসমান অদৃশ্য শক্তি (আমাদের ক্ষেত্রে, BLE বিজ্ঞাপন) সনাক্ত করতে ব্যবহার করি। কিন্তু এই ভূত-শিকারের গ্যাজেট আসলে কীভাবে কাজ করে?
দ্য আর্কিটেকচার:এ পিক বিহাইন্ড দ্য কার্টেন
উচ্চ স্তরে, প্রক্রিয়াটি বেশ সহজবোধ্য। আপনার অ্যাপ, তার নিজের ছোট্ট জগতে আরামদায়কভাবে বসবাস করে, সিদ্ধান্ত নেয় যে এটি কিছু BLE ডিভাইস খুঁজতে চায়। এটি BluetoothLeScanner-এর একটি দৃষ্টান্ত গ্রহণ করে এবং বলে, "আরে, জিনিসপত্র খুঁজতে যান।"
হুডের নিচে, অনেক কিছু ঘটছে। ব্লুটুথলেস্ক্যানার অ্যান্ড্রয়েড ব্লুটুথ স্ট্যাকের সাথে কথা বলে (কোডনাম "ফ্লুরাইড," যা আপনার ডেন্টিস্টের জন্য খুব গর্বিত বলে মনে হয়)। স্ট্যাকটি তখন ডিভাইসের ব্লুটুথ কন্ট্রোলারের সাথে যোগাযোগ করে, প্রকৃত হার্ডওয়্যার যা রেডিও তরঙ্গ প্রেরণ এবং গ্রহণ করে। এটি একটি ক্লাসিক কেস "এটি যতটা দেখায় তার চেয়ে বেশি জটিল।"
বর্ণমালার স্যুপ:GATT, GAP, এবং বন্ধুরা
আপনি যখন BLE-এর জগতে প্রবেশ করেন, তখন আপনি দ্রুত আদ্যক্ষরগুলির একটি সম্পূর্ণ গুচ্ছের মধ্যে চলে যাবেন। আতঙ্কিত হবেন না! তারা দেখতে যতটা ভয়ঙ্কর নয়। বোঝার জন্য সবচেয়ে গুরুত্বপূর্ণ দুটি হল GAP এবং GATT।
-
GAP (জেনারিক অ্যাক্সেস প্রোফাইল): ডিভাইসগুলি কীভাবে একে অপরের সাথে আবিষ্কৃত হয় এবং সংযুক্ত হয় সে সম্পর্কেই এটি। একটি নাইটক্লাবে GAP কে বাউন্সার হিসাবে ভাবুন। এটা ঠিক করে কে কার সাথে কথা বলবে। এটি বিজ্ঞাপন পরিচালনা করে (যন্ত্রটি চিৎকার করে "আমি এখানে!") এবং স্ক্যানিং (আপনার অ্যাপ সেই চিৎকারের জন্য শুনছে)। আমাদের ব্লুটুথলেস্ক্যানার হল GAP-পদে একটি মূল খেলোয়াড়৷
৷ -
GATT (জেনারিক অ্যাট্রিবিউট প্রোফাইল): একবার দুটি ডিভাইস সংযুক্ত হলে, GATT দায়িত্ব নেয়। তারা কীভাবে ডেটা বিনিময় করে তা নির্ধারণ করে। GATT কে নাইটক্লাবের ভিতরে ঘটছে প্রকৃত কথোপকথন হিসাবে ভাবুন। এটি সমস্ত পরিষেবা, বৈশিষ্ট্য এবং বর্ণনাকারী সম্পর্কে। একটি ডিভাইসে একটি "হার্ট রেট সার্ভিস" থাকতে পারে যার মধ্যে একটি "হার্ট রেট পরিমাপের বৈশিষ্ট্য" রয়েছে। আপনার অ্যাপটি প্রয়োজনীয় ডেটা পেতে এই বৈশিষ্ট্যগুলি থেকে পড়ে বা লেখে৷
৷
স্ক্যান করার উদ্দেশ্যে, আমরা বেশিরভাগই GAP এর জগতে বাস করছি। আমরা ক্লাবের বাইরে দাঁড়িয়ে আকর্ষণীয় বিজ্ঞাপন শুনছি।
দ্য স্ক্যানিং লাইফসাইকেল:একটি নাটকীয় নাটক ইন থ্রি অ্যাক্টস
একটি ব্লুটুথ স্ক্যানের জীবন একটি সহজ, কিন্তু মার্জিত, নাটক৷
৷-
আইন I: প্রস্তুতি. আপনার অ্যাপটি স্ক্যান করার সময় নির্ধারণ করে। এটি BluetoothLeScanner পায়, স্ক্যানফিল্টারগুলির একটি সেট তৈরি করে (শুধুমাত্র নির্দিষ্ট ডিভাইসগুলি খুঁজে পেতে) এবং স্ক্যানসেটিংস (কীভাবে স্ক্যান করতে হয় তা নির্ধারণ করতে, যেমন আমাদের নতুন প্যাসিভ মোড), এবং একটি স্ক্যানকলব্যাক সংজ্ঞায়িত করে৷
-
আইন II: স্ক্যান. আপনার অ্যাপ কল startScan()। ব্লুটুথ রেডিও প্রাণবন্ত হয়ে ওঠে, আপনার ফিল্টারের সাথে মেলে এমন বিজ্ঞাপনের জন্য শোনা। যখন এটি একটি খুঁজে পায়, তখন এটি আপনার স্ক্যানকলব্যাকে onScanResult() পদ্ধতির মাধ্যমে আপনার অ্যাপে রিপোর্ট করে৷
-
আইন III: দ্য এন্ড। যখন আপনার অ্যাপটি যথেষ্ট পরিমাণে থাকে (বা, আরও গুরুত্বপূর্ণভাবে, আপনি যা খুঁজছেন তা পেয়ে গেলে), এটি স্টপস্ক্যান() বলে। রেডিও বন্ধ হয়ে যায় এবং সবকিছু আবার শান্ত হয়। আপনার স্ক্যান করা হয়ে গেলে সর্বদা আপনার স্ক্যান বন্ধ করা অত্যন্ত গুরুত্বপূর্ণ। একটি দুর্বৃত্ত স্ক্যান হল ব্যবহারকারীদের কাছ থেকে "আমার ব্যাটারি এক ঘন্টার মধ্যে মারা যায়" অভিযোগের এক নম্বর কারণ৷
এবং এটি সংক্ষেপে BluetoothLeScanner। এটি BLE আবিষ্কারের জগতে আমাদের প্রবেশদ্বার। এটি শক্তিশালী, এটি জটিল, কিন্তু আমরা যেমন শিখছি, প্রতিটি নতুন অ্যান্ড্রয়েড রিলিজের সাথে এটি আরও স্মার্ট এবং আরও দক্ষ হয়ে উঠছে। এখন যেহেতু আমরা আমাদের টুল জানি, আসুন আমাদের হাত নোংরা করি এবং আমাদের প্রথম প্যাসিভ স্ক্যানার তৈরি করি!
হ্যান্ডস-অন:আপনার প্রথম প্যাসিভ স্ক্যানার তৈরি করা
তত্ত্বটি দুর্দান্ত, তবে আসুন সত্য কথা বলি, আমরা বিকাশকারী। আমরা কাজ করে শিখি (বা স্ট্যাক ওভারফ্লো থেকে কপি পেস্ট করে)। আমাদের হাতা গুটিয়ে নেওয়ার, Android স্টুডিও চালু করার এবং কিছু তৈরি করার সময় এসেছে৷ আমরা একটি সাধারণ অ্যাপ তৈরি করতে যাচ্ছি যা আমাদের নতুন পাওয়া প্যাসিভ স্ক্যানিং ক্ষমতা ব্যবহার করে আশেপাশের BLE ডিভাইসগুলি খুঁজে পেতে।
ধাপ 1:অনুমতি অনুসন্ধান
আমরা কোটলিনের একটি একক লাইন লিখার আগে, আমাদের অবশ্যই অ্যান্ড্রয়েড অনুমতি দেবতাদের সন্তুষ্ট করতে হবে। এটি একটি পবিত্র এবং প্রায়ই হতাশাজনক আচার। ব্লুটুথ স্ক্যানিংয়ের জন্য, কয়েক বছর ধরে নিয়মগুলি কিছুটা পরিবর্তিত হয়েছে৷
৷
প্রথমে, আপনার AndroidManifest.xml খুলুন এবং নিম্নলিখিত যোগ করুন:
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<!-- For Android 12 (API 31) and above -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<!-- For older versions, you needed location permissions -->
<!-- You might still need this if you support older devices -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
আমরা উপরে ঘোষিত অনুমতিগুলির দিকে তাকিয়ে, আপনি Android এর ব্লুটুথ অনুমতি মডেলের বিবর্তনটি রিয়েল-টাইমে চলছে দেখতে পাবেন৷
প্রথম দুটি অনুমতি, BLUETOOTH এবং BLUETOOTH_ADMIN , পুরানো প্রহরী হয়. তারা অ্যান্ড্রয়েডের প্রথম দিন থেকে প্রায় আছে এবং মৌলিক ব্লুটুথ কার্যকারিতা এবং ডিভাইসগুলি আবিষ্কার করার ক্ষমতা প্রদান করে। তারপর আমাদের আছে BLUETOOTH_SCAN , যা Android 12 (API 31) এ চালু করা হয়েছিল এবং Google গোপনীয়তা সম্পর্কে কীভাবে চিন্তা করে তার একটি বড় পরিবর্তনের প্রতিনিধিত্ব করে৷
হ্যাঁ, আপনি এটা ঠিক দেখছেন. পুরানো দিনগুলিতে (Android 12 এর আগে), Google সিদ্ধান্ত নিয়েছিল যে একটি ব্লুটুথ ডিভাইস খুঁজে পাওয়া মূলত আপনার ব্যবহারকারীর সঠিক অবস্থান জানার মতই। এটি এক ধরণের অর্থবোধক:সর্বোপরি, আপনি যদি দেখতে পান যে কোন ব্লুটুথ বীকন কাছাকাছি রয়েছে, আপনি আপনার অবস্থান ত্রিভুজ করতে পারেন। তবে হেডফোনের একটি জোড়া খুঁজে পাওয়ার জন্য অবস্থান জিজ্ঞাসা করাও কিছুটা ভয়ঙ্কর ছিল। এটি এমন বিশ্রী পরিস্থিতির দিকে পরিচালিত করে যেখানে ব্যবহারকারীরা একটি সাধারণ ব্লুটুথ স্ক্যানার অ্যাপ দেখতে পাবে যা তাদের সঠিক অবস্থান জানতে চাইবে এবং বোধগম্যভাবে সন্দেহজনক হয়ে উঠবে।
ধন্যবাদ, Android 12 এর সাথে, তারা BLUETOOTH_SCAN চালু করেছে অনুমতি, যা অনেক বেশি বুদ্ধিমান। এই অনুমতি অবশেষে অ্যাপগুলিকে লোকেশন অ্যাক্সেসের জন্য জিজ্ঞাসা করার প্রয়োজন ছাড়াই ব্লুটুথ ডিভাইসগুলির জন্য স্ক্যান করার অনুমতি দেয়, যা ব্যবহারকারীর দৃষ্টিকোণ থেকে অনেক বেশি অর্থবোধ করে। রানটাইমে আপনাকে এখনও এই অনুমতির অনুরোধ করতে হবে, তবে অন্তত আপনাকে আপনার ব্যবহারকারীদের ব্যাখ্যা করতে হবে না কেন আপনার সাধারণ গ্যাজেট-অনুসন্ধানকারী অ্যাপটি তারা কোথায় থাকে তা জানতে চায়।
যাইহোক, অবস্থান অ্যাক্সেসের জন্য সেই শেষ দুটি অনুমতি লক্ষ্য করুন। এগুলো পুরনো ব্যবস্থার অবশিষ্টাংশ। আপনি যদি এমন একটি অ্যাপ তৈরি করেন যা Android 11 বা তার নীচের সংস্করণে চলমান পুরানো ডিভাইসগুলিকে সমর্থন করতে হবে, তাহলে আপনাকে পিছনের সামঞ্জস্যের জন্য আপনার ম্যানিফেস্টে এই অবস্থানের অনুমতিগুলি রাখতে হবে। আধুনিক ডিভাইসে, BLUETOOTH_SCAN অনুমতি একাই কাজ করবে।
ধাপ 2:কোড জাগ্রত হয়
ঠিক আছে, মজার অংশে আসা যাক। আপনার অ্যাক্টিভিটি বা ফ্র্যাগমেন্টে প্যাসিভ স্ক্যানার কীভাবে প্রয়োগ করবেন তার একটি ব্রেকডাউন এখানে রয়েছে।
স্ক্যানার পান
প্রথমে, আমাদের BluetoothLeScanner-এর একটি উদাহরণ পেতে হবে৷
৷private val bluetoothAdapter: BluetoothAdapter? by lazy {
val bluetoothManager = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
bluetoothManager.adapter
}
private val bleScanner: BluetoothLeScanner? by lazy {
bluetoothAdapter?.bluetoothLeScanner
}
আসুন উপরের কোডে কী ঘটছে তা ভেঙে দেওয়া যাক। আমরা কোটলিনের lazy ব্যবহার করছি প্রতিনিধি, যা বলার একটি অভিনব উপায় "আমার আসলে এটির প্রয়োজন না হওয়া পর্যন্ত এই বস্তুটি তৈরি করবেন না।" এটি একটি ভাল অভ্যাস কারণ ব্লুটুথ অ্যাডাপ্টার পাওয়ার সাথে সিস্টেম কল জড়িত, এবং যদি আমরা এটি ব্যবহার না করি তবে সেই কাজটি করার কোন মানে নেই৷
প্রথমে, আমরা BluetoothManager ধরি সিস্টেম পরিষেবা থেকে। BluetoothManager চিন্তা করুন আপনার ডিভাইসে সমস্ত জিনিস ব্লুটুথের দারোয়ান হিসাবে। এই ম্যানেজার থেকে, আমরা BluetoothAdapter পাই , যা আপনার ডিভাইসের শারীরিক ব্লুটুথ হার্ডওয়্যার প্রতিনিধিত্ব করে। লক্ষ্য করুন যে আমরা এটিকে বাতিলযোগ্য হিসাবে ঘোষণা করছি (BluetoothAdapter? ) কারণ, বিশ্বাস করুন বা না করুন, প্রতিটি অ্যান্ড্রয়েড ডিভাইসে ব্লুটুথ থাকে না। কিছু ট্যাবলেট বা অস্পষ্ট ডিভাইসে হার্ডওয়্যার নাও থাকতে পারে, তাই আমাদের সেই সম্ভাবনার জন্য প্রস্তুত থাকতে হবে।
একবার আমাদের কাছে অ্যাডাপ্টার হয়ে গেলে, আমরা এটিকে BluetoothLeScanner চাইতে পারি . এটিই আসল বস্তু যা আমরা আমাদের স্ক্যান করতে ব্যবহার করব। আবার, আমরা নিরাপদ কল অপারেটর ব্যবহার করছি (?. ) কারণ অ্যাডাপ্টারটি যদি শূন্য হয় (কোন ব্লুটুথ হার্ডওয়্যার নেই), আমরা অবশ্যই এটি থেকে একটি স্ক্যানার পেতে পারি না। এই রক্ষণাত্মক প্রোগ্রামিংকে বিভ্রান্তিকর মনে হতে পারে, কিন্তু এটিই এমন অ্যাপগুলিকে আলাদা করে যা রহস্যজনকভাবে ক্র্যাশ করা অ্যাপগুলিকে এমন অ্যাপ থেকে আলাদা করে যা সুন্দরভাবে এজ কেসগুলি পরিচালনা করে।
কলব্যাক সংজ্ঞায়িত করুন
এখানেই ম্যাজিক ঘটে। ScanCallback হল একটি বস্তু যা স্ক্যান ফলাফলের জন্য শুনবে। আমাদের দুটি পদ্ধতি ওভাররাইড করতে হবে:onScanResult এবং onScanFailed.
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
// We found a device!
// The 'result' object contains the device, RSSI, and advertisement data.
Log.d("BleScanner", "Found device: ${result.device.address}, RSSI: ${result.rssi}")
}
override fun onScanFailed(errorCode: Int) {
// This is the universe's way of telling you to take a break.
// Or that something went horribly wrong.
Log.e("BleScanner", "Scan failed with error code: $errorCode")
}
}
ScanCallback আমরা উপরে সংজ্ঞায়িত করেছি ব্লুটুথ জগতে আপনার অ্যাপের কান। যখন স্ক্যানার একটি ডিভাইস খুঁজে পায়, তখন এটি শুধুমাত্র তথ্য কোথাও সংরক্ষণ করে না, এটি এই কলব্যাক অবজেক্টের মাধ্যমে সক্রিয়ভাবে আপনার অ্যাপে কল করে। এটি ক্লাসিক ইভেন্ট-চালিত প্রোগ্রামিং, এবং মূল থ্রেড ব্লক না করেই Android কীভাবে আপনার অ্যাপকে প্রতিক্রিয়াশীল রাখে।
onScanResult প্রতিবার স্ক্যানার আপনার ফিল্টারগুলির সাথে মেলে এমন একটি ডিভাইস আবিষ্কার করার সময় পদ্ধতিটি বলা হয় (বা আপনি যদি ফিল্টার ব্যবহার না করেন তবে যেকোনো ডিভাইস)। result প্যারামিটার হল তথ্যের ভান্ডার। এতে BluetoothDevice আছে অবজেক্ট (যার ডিভাইসের MAC ঠিকানা এবং নাম রয়েছে), RSSI মান (প্রাপ্ত সংকেত শক্তি নির্দেশক - মূলত ডিভাইসটি কতটা কাছাকাছি, উচ্চ সংখ্যার মানে কাছাকাছি), এবং অপরিশোধিত বিজ্ঞাপনের ডেটা যা ডিভাইসটি সম্প্রচার করছে।
উপরের আমাদের সাধারণ উদাহরণে, আমরা শুধু MAC ঠিকানা এবং RSSI লগ করছি, কিন্তু একটি বাস্তব অ্যাপে, আপনি সম্ভবত আপনার UI আপডেট করতে চান, ডিভাইসটিকে একটি তালিকায় যুক্ত করতে চান, অথবা একটি সংযোগ ট্রিগার করতে চান৷
callbackType প্যারামিটার আপনাকে বলে কেন এই কলব্যাক ট্রিগার করা হয়েছে. এটা CALLBACK_TYPE_ALL_MATCHES হতে পারে (ডিফল্ট, মানে "এখানে প্রতিটি ডিভাইস আমরা খুঁজে পেয়েছি"), CALLBACK_TYPE_FIRST_MATCH (আমরা এই ডিভাইসটি প্রথমবার দেখেছি), অথবা CALLBACK_TYPE_MATCH_LOST (আমরা এই ডিভাইসটি কিছু সময়ের মধ্যে দেখিনি, তাই সম্ভবত এটি ছেড়ে গেছে)। আমরা উন্নত বিভাগে এই ধরনের আরও গভীরে ডুব দেব।
তারপর onScanFailed আছে , আমরা সবাই আশা করি যে পদ্ধতিটি কখনই বলা হয় না কিন্তু আমাদের একেবারে হ্যান্ডেল করতে হবে। স্ক্যানে কিছু বিপর্যয়করভাবে ভুল হলে এটি চালু করা হয়। হতে পারে ব্লুটুথ অ্যাডাপ্টারটি স্ক্যানের মাঝামাঝি বন্ধ হয়ে গেছে, হতে পারে আপনার অ্যাপের সঠিক অনুমতি নেই, বা ব্লুটুথ কন্ট্রোলারের একটি খারাপ দিন ছিল। errorCode কি ভুল হয়েছে সে সম্পর্কে আপনাকে একটি ইঙ্গিত দেবে, এবং আপনার সর্বদা এটি লগ করা উচিত এবং এটিকে সুন্দরভাবে পরিচালনা করা উচিত - সম্ভবত ব্যবহারকারীকে একটি বার্তা দেখিয়ে বা বিলম্বের পরে স্ক্যানটি পুনরায় চালু করার চেষ্টা করে৷
স্ক্যান কনফিগার করুন
এখন, আমরা আমাদের স্ক্যান সেটিংস তৈরি করি। এখানেই আমরা Android কে বলি যে আমরা একটি প্যাসিভ, ব্যাটারি-সাশ্রয়ী নিনজা হতে চাই।
val scanSettings = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER) // Let's be nice to the battery
.setCallbackType(ScanSettings.CALLBACK_TYPE_ALL_MATCHES)
.setMatchMode(ScanSettings.MATCH_MODE_AGGRESSIVE)
.setNumOfMatches(ScanSettings.MATCH_NUM_ONE_ADVERTISEMENT) // Report each ad once
.setReportDelay(0L) // Report immediately
// And here's the star of the show!
.setScanType(ScanSettings.SCAN_TYPE_PASSIVE)
.build()
ScanSettings আমরা উপরে যে বস্তুটি তৈরি করছি তা ব্লুটুথ স্ক্যানারের জন্য একটি বিশদ নির্দেশিকা ম্যানুয়ালের মতো। প্রতিটি পদ্ধতিতে স্ক্যানটি ঠিক কীভাবে আচরণ করা উচিত তা সূক্ষ্ম-টিউনগুলিকে কল করে এবং এই সেটিংসগুলি সঠিকভাবে পাওয়া একটি ব্যাটারি-বান্ধব অ্যাপ এবং কয়েক ঘণ্টার মধ্যে আনইনস্টল হয়ে যাওয়া অ্যাপের মধ্যে পার্থক্য।
এর প্রতিটি সেটিং মাধ্যমে পদচারণা করা যাক. প্রথমে, setScanMode(SCAN_MODE_LOW_POWER) স্ক্যানারকে একটি কম-পাওয়ার স্ক্যানিং মোড ব্যবহার করতে বলে, যার মানে এটি ক্রমাগত না হয়ে বিরতিতে স্ক্যান করবে। এটি বেশিরভাগ ব্যবহারের ক্ষেত্রে উপযুক্ত যেখানে আপনার তাত্ক্ষণিক ফলাফলের প্রয়োজন নেই এবং ব্যাটারি লাইফ সংরক্ষণ করতে চান৷ স্ক্যানার জেগে উঠবে, একটু স্ক্যান করবে, ঘুমাবে এবং পুনরাবৃত্তি করবে। এটি পাওয়ার ন্যাপ নেওয়ার ব্লুটুথ সমতুল্য।
এরপরে, setCallbackType(CALLBACK_TYPE_ALL_MATCHES) মানে প্রতিবার স্ক্যানার একটি ম্যাচিং ডিভাইস খুঁজে পেলে আমরা অবহিত হতে চাই। এটি ডিফল্ট আচরণ এবং আপনি বেশিরভাগ সময় ব্যবহার করবেন। আমরা আগে উল্লেখ করেছি, আপনি CALLBACK_TYPE_FIRST_MATCHও ব্যবহার করতে পারেন অথবা CALLBACK_TYPE_MATCH_LOST আরও পরিশীলিত উপস্থিতি সনাক্তকরণের জন্য৷
setMatchMode(MATCH_MODE_AGGRESSIVE) সেটিং নিয়ন্ত্রণ করে যে হার্ডওয়্যার আপনার ফিল্টারগুলির সাথে ডিভাইসগুলিকে কতটা আক্রমনাত্মকভাবে মেলানোর চেষ্টা করবে৷ MATCH_MODE_AGGRESSIVE মানে "যদিও আপনি 100% নিশ্চিত না হন তাহলেও দ্রুত মেলে," যখন MATCH_MODE_STICKY মানে "প্রতিবেদন করার আগে আপনি সত্যিই নিশ্চিত না হওয়া পর্যন্ত অপেক্ষা করুন।" আক্রমণাত্মক মোড আপনাকে দ্রুত ফলাফল দেয় তবে মাঝে মাঝে আপনাকে মিথ্যা ইতিবাচক দিতে পারে।
তারপর আমাদের আছে setNumOfMatches(MATCH_NUM_ONE_ADVERTISEMENT) , যা স্ক্যানারকে একটি ডিভাইস থেকে শুধুমাত্র একটি বিজ্ঞাপন দেখার পরে রিপোর্ট করতে বলে৷ বিকল্প হল MATCH_NUM_FEW_ADVERTISEMENT , যা রিপোর্ট করার আগে একাধিক বিজ্ঞাপনের জন্য অপেক্ষা করে। একটি বিজ্ঞাপন ব্যবহার করলে আপনি দ্রুত আবিষ্কার করতে পারবেন, কিছুর জন্য অপেক্ষা করলে এমন ডিভাইস থেকে মিথ্যা ইতিবাচকতা কমে যাবে
setReportDelay(0L) সেটিং অত্যন্ত গুরুত্বপূর্ণ। 0 এর বিলম্ব মানে "ফল অবিলম্বে রিপোর্ট করুন।" আপনি যদি এটি সেট করেন, বলুন, 5000 মিলিসেকেন্ডে, স্ক্যানারটি ফলাফল ব্যাচ আপ করবে এবং প্রতি 5 সেকেন্ডে সেগুলি সরবরাহ করবে। ব্যাচিং ব্যাকগ্রাউন্ড স্ক্যানিংয়ের জন্য দুর্দান্ত (যেমন আমরা উন্নত বিভাগে আলোচনা করেছি), কিন্তু ফোরগ্রাউন্ড স্ক্যানিংয়ের জন্য যেখানে ব্যবহারকারী সক্রিয়ভাবে অপেক্ষা করছে, আপনি যা চান তাৎক্ষণিক রিপোর্টিং।
এবং অবশেষে, আমাদের অনুষ্ঠানের তারকা:setScanType(SCAN_TYPE_PASSIVE) . এটি Android 16 QPR2-এর নতুন এপিআই যা আমাদের স্ক্যানারকে নীরব শ্রোতায় রূপান্তরিত করে। এটি শোনা প্রতিটি ডিভাইসে সক্রিয়ভাবে স্ক্যান অনুরোধ পাঠানোর পরিবর্তে, এটি কেবল বাতাসে ভাসমান বিজ্ঞাপনগুলি শোনে। স্ক্যান করার সময় এই একক সেটিং নাটকীয়ভাবে আপনার অ্যাপের ব্যাটারি খরচ কমাতে পারে। এটি সেই বৈশিষ্ট্য যার জন্য আমরা অপেক্ষা করছিলাম, এবং এটি মহিমান্বিত৷
স্ক্যান শুরু এবং বন্ধ করুন
অবশেষে, আমাদের স্ক্যান শুরু এবং বন্ধ করার জন্য আমাদের ফাংশন প্রয়োজন। মনে রাখবেন:সবসময় আপনার স্ক্যান বন্ধ করুন! একটি ভুলে যাওয়া স্ক্যান হল একটি ব্যাটারি-হত্যাকারী দানব৷
৷private fun startBleScan() {
// Don't forget to request permissions first!
if (bleScanner != null) {
// You can add ScanFilters here to search for specific devices
val scanFilters: List<ScanFilter> = listOf()
bleScanner.startScan(scanFilters, scanSettings, scanCallback)
Log.d("BleScanner", "Scan started.")
} else {
Log.e("BleScanner", "Bluetooth is not available.")
}
}
private fun stopBleScan() {
if (bleScanner != null) {
bleScanner.stopScan(scanCallback)
Log.d("BleScanner", "Scan stopped.")
}
}
উপরের এই দুটি ফাংশন হল আপনার ব্লুটুথ স্ক্যানারের জন্য চালু/বন্ধ সুইচ, এবং সেগুলি কতটা গুরুত্বপূর্ণ তার জন্য প্রতারণামূলকভাবে সহজ। আসুন প্রতিটিতে কী ঘটছে তা ভেঙে দেওয়া যাক।
startBleScan()-এ , আমরা প্রথমে bleScanner কিনা তা পরীক্ষা করি শূন্য নয়। এটি আমাদের নিরাপত্তা জাল:ডিভাইসটিতে ব্লুটুথ হার্ডওয়্যার না থাকলে বা ব্লুটুথ অক্ষম থাকলে, স্ক্যানারটি শূন্য হয়ে যাবে এবং আমরা একটি নাল অবজেক্টে পদ্ধতি কল করার চেষ্টা করে ক্র্যাশ করতে চাই না। স্ক্যানার বিদ্যমান থাকলে, আমরা startScan() কল করি তিনটি প্যারামিটার সহ:ScanFilter এর একটি তালিকা বস্তু, আমাদের সাবধানে তৈরি করা ScanSettings , এবং ScanCallback আমরা আগে সংজ্ঞায়িত করেছি।
scanFilters আমাদের উদাহরণে তালিকা বর্তমানে খালি, যার মানে "সমস্ত BLE ডিভাইস খুঁজুন।" একটি বাস্তব-বিশ্বের অ্যাপে, আপনি সাধারণত আপনার অনুসন্ধানকে সংকুচিত করতে এখানে ফিল্টার যোগ করবেন।
উদাহরণস্বরূপ, আপনি যদি এমন একটি অ্যাপ তৈরি করেন যা শুধুমাত্র হার্ট রেট মনিটরগুলির সাথে কাজ করে, তাহলে আপনি একটি ফিল্টার তৈরি করবেন যা শুধুমাত্র হার্ট রেট পরিষেবা UUID-এর বিজ্ঞাপনের ডিভাইসগুলির সাথে মেলে৷ পারফরম্যান্স এবং ব্যাটারি লাইফ উভয়ের জন্যই এটি অত্যন্ত গুরুত্বপূর্ণ:যখন আপনি শুধুমাত্র ফিটনেস ট্র্যাকারের কথা চিন্তা করেন তখন কেন প্রতিটি এলোমেলো ব্লুটুথ টুথব্রাশের জন্য আপনার অ্যাপটি জাগিয়ে তুলবেন?
startScan() পদ্ধতিটি স্ক্যানিং প্রক্রিয়া বন্ধ করে দেয়। এই বিন্দু থেকে, ব্লুটুথ রেডিও সক্রিয়ভাবে (বা আমাদের ক্ষেত্রে, নিষ্ক্রিয়ভাবে) বিজ্ঞাপনগুলি এবং আপনার scanCallback শুনছে ফলাফল পেতে শুরু করবে। এটি একটি অ্যাসিঙ্ক্রোনাস অপারেশন, যার অর্থ আপনার কোড এখানে ব্লক করে না ফলাফলের জন্য অপেক্ষা করে – বরং, এটি কার্যকর হতে থাকে, এবং ফলাফলগুলি যখনই পাওয়া যায় কলব্যাকের মাধ্যমে আসে৷
এখন stopBleScan() সম্পর্কে কথা বলা যাক , যা আপনার লেখার সবচেয়ে গুরুত্বপূর্ণ ফাংশন হতে পারে। যখন আপনি stopScan() কল করেন আপনার কলব্যাকের সাথে, আপনি ব্লুটুথ রেডিওকে বলছেন, "ঠিক আছে, আমরা এখানে শেষ করেছি, আপনি আবার ঘুমাতে যেতে পারেন।" এটি অবিলম্বে স্ক্যানিং প্রক্রিয়া বন্ধ করে এবং সংস্থানগুলি প্রকাশ করে৷
বোঝার মতো গুরুত্বপূর্ণ বিষয় হল যে আপনি যদি এটিকে কল না করেন, তাহলে স্ক্যানটি অনির্দিষ্টকালের জন্য চলতে থাকবে, আপনার ব্যবহারকারীর ব্যাটারি ভ্যাম্পায়ারের মতো নিঃশেষ করে দেবে যা আপনি খেতে পারেন এমন ব্লাড ব্যাঙ্কে। এই কারণেই আমরা এটিকে এত জোর দিই:একটি ভুলে যাওয়া stopScan() ব্লুটুথ অ্যাপে ব্যাটারি নিষ্কাশনের অভিযোগের সবচেয়ে সাধারণ কারণগুলির মধ্যে একটি হল কল৷
লক্ষ্য করুন যে আমরা একই scanCallback পাস করছি আপত্তি stopScan() যেটি আমরা startScan() এ ব্যবহার করেছি . এইভাবে অ্যান্ড্রয়েড জানে কোন স্ক্যানটি বন্ধ করতে হবে – আপনার তাত্ত্বিকভাবে বিভিন্ন কলব্যাকের সাথে একাধিক স্ক্যান চলমান থাকতে পারে (যদিও এটি খুব কমই একটি ভাল ধারণা)। সর্বদা নিশ্চিত করুন যে আপনি একই কলব্যাক রেফারেন্স ব্যবহার করে শুরু করেছিলেন সেই একই স্ক্যানটি বন্ধ করছেন৷
এটি একসাথে রাখা
এখানে একটি সম্পূর্ণ উদাহরণ যা আপনি একটি ক্রিয়াকলাপে ড্রপ করতে পারেন৷ শুধু রানটাইম অনুমতিগুলি পরিচালনা করতে মনে রাখবেন!
// In your Activity class
class MainActivity : AppCompatActivity() {
// ... (lazy properties for adapter and scanner from above)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// ... your UI setup ...
// Example: Start scan on button click
val startButton = findViewById<Button>(R.id.startButton)
startButton.setOnClickListener {
// You MUST request permissions before calling this!
startBleScan()
}
// Example: Stop scan on another button click
val stopButton = findViewById<Button>(R.id.stopButton)
stopButton.setOnClickListener {
stopBleScan()
}
}
// ... (scanCallback, startBleScan, stopBleScan functions from above)
override fun onPause() {
super.onPause()
// Always stop scanning when the activity is not visible.
stopBleScan()
}
}
উপরের সম্পূর্ণ উদাহরণটি দেখায় কিভাবে একটি বাস্তব ক্রিয়াকলাপে সমস্ত অংশ একসাথে ফিট করে। এটি একটি ন্যূনতম কিন্তু কার্যকরী ব্লুটুথ স্ক্যানার যা আপনি আসলে চালাতে পারেন। আসুন আমরা এখানে ব্যবহার করছি এমন কয়েকটি গুরুত্বপূর্ণ প্যাটার্ন হাইলাইট করি।
প্রথমত, লক্ষ্য করুন কিভাবে আমরা বোতাম ক্লিকের মাধ্যমে ব্যবহারকারীর ক্রিয়াকলাপের সাথে স্ক্যান লাইফসাইকেল সংযুক্ত করছি। এটি একটি সাধারণ প্যাটার্ন:ব্যবহারকারী স্পষ্টভাবে স্ক্যান শুরু করে এবং বন্ধ করে দেয়, অ্যাপটি যখন ব্লুটুথ ব্যবহার করে তখন তাদের নিয়ন্ত্রণ করে। এটি ভাল UX এবং ব্যাটারি লাইফ উভয়ের জন্যই ভাল, কারণ স্ক্যান শুধুমাত্র তখনই চলে যখন ব্যবহারকারী এটি করতে চায়।
কিন্তু এখানে সত্যিই গুরুত্বপূর্ণ অংশ:onPause() ওভাররাইড এটি একটি গুরুত্বপূর্ণ নিরাপত্তা জাল। যখন আপনার কার্যকলাপ ব্যাকগ্রাউন্ডে চলে যায় (হয়তো ব্যবহারকারী হোম বোতাম টিপেছেন, অথবা তারা অন্য অ্যাপে স্যুইচ করেছেন), onPause() বলা হয়, এবং আমরা অবিলম্বে স্ক্যান বন্ধ করি। এটি অপরিহার্য কারণ ব্যবহারকারী যদি আপনার অ্যাপটি দেখতে না পারে তবে তাদের স্ক্যান ফলাফলের প্রয়োজন নেই এবং তাদের ব্যাটারি নিষ্কাশন করার কোন কারণ নেই। এই প্যাটার্নটি নিশ্চিত করে যে ব্যবহারকারী "স্টপ" বোতাম টিপতে ভুলে গেলেও, স্ক্যানটি পটভূমিতে চিরতরে চলবে না৷
আপনি হয়ত ভাবছেন, "কী সম্পর্কে onResume() ? ব্যবহারকারী ফিরে এলে কি আমাদের স্ক্যানটি পুনরায় চালু করা উচিত নয়?" এটি একটি নকশা সিদ্ধান্ত. কিছু অ্যাপে, আপনি onResume()-এ স্বয়ংক্রিয়ভাবে স্ক্যান করা পুনরায় চালু করতে চাইতে পারেন . অন্যদের মধ্যে, আপনি ব্যবহারকারীকে স্পষ্টভাবে আবার "স্টার্ট" চাপতে চাইতে পারেন। এটি আপনার ব্যবহারের ক্ষেত্রে নির্ভর করে। একটি ডিভাইস-ফাইন্ডিং অ্যাপের জন্য যেখানে ব্যবহারকারী সক্রিয়ভাবে অনুসন্ধান করছে, স্বয়ংক্রিয়-পুনরায় শুরু করা অর্থপূর্ণ। ব্যাকগ্রাউন্ডে চলা একটি মনিটরিং অ্যাপের জন্য, আপনি আরও স্পষ্ট নিয়ন্ত্রণ চাইতে পারেন।
একটি গুরুত্বপূর্ণ জিনিস যা আমরা এই উদাহরণে দেখাইনি তা হল রানটাইম অনুমতি পরিচালনা। আমরা ম্যানিফেস্টে ঘোষিত সেই অনুমতিগুলি মনে রাখবেন? অ্যান্ড্রয়েড 6.0 এবং তার উপরে, আপনি কেবল সেগুলি ঘোষণা করতে পারবেন না, আপনাকে আসলে রানটাইমে ব্যবহারকারীর কাছ থেকে তাদের অনুরোধ করতে হবে। startBleScan() কল করার আগে , আপনার কাছে প্রয়োজনীয় অনুমতি আছে কিনা তা পরীক্ষা করা উচিত এবং যদি না থাকে তবে ActivityCompat.requestPermissions() ব্যবহার করে তাদের অনুরোধ করুন . আপনি যদি যথাযথ অনুমতি ছাড়াই একটি স্ক্যান শুরু করার চেষ্টা করেন, তাহলে এটি নীরবে ব্যর্থ হবে (অথবা জোরে, Android সংস্করণের উপর নির্ভর করে), এবং আপনি কেন কিছু কাজ করছে না তা ভেবে আপনার মাথা চুলকাতে থাকবে।
এবং সেখানে আপনি এটি আছে! আপনি এইমাত্র আপনার প্রথম AOSP 16 প্যাসিভ ব্লুটুথ স্ক্যানার তৈরি করেছেন৷ এটি চর্বিহীন, এটি গড়, এবং এটি অবিশ্বাস্যভাবে শক্তি-দক্ষ। স্ক্যানারটি BLE বিজ্ঞাপনের জন্য নীরবে শোনে, আপনার কলব্যাকের মাধ্যমে সেগুলিকে রিপোর্ট করে এবং যখন এটির প্রয়োজন হয় না তখন সুন্দরভাবে থামে৷
এখন, আমাদের পরবর্তী বিষয়ের দিকে যাওয়া যাক:যখন কিছু ভুল হয়ে যায় তখন কী করতে হবে। ব্রেকআপ নিয়ে কথা বলার সময় এসেছে... ব্লুটুথ বন্ড ব্রেকআপ, অর্থাৎ।
ডিপ ডাইভ #2:ব্লুটুথ বন্ড হারানোর কারণ
আহ, ব্লুটুথ বন্ড। এটি একটি সুন্দর, পবিত্র জিনিস। এটি বন্ধুত্বের ব্রেসলেট বিনিময়ের ডিজিটাল সমতুল্য। আপনি যখন আপনার ফোনকে আপনার হেডফোনের সাথে সংযুক্ত করেন, তখন আপনি একটি দীর্ঘমেয়াদী, বিশ্বস্ত সম্পর্ক তৈরি করেন। তারা গোপন কীগুলি ভাগ করে নেয়, তারা একে অপরকে মনে রাখে এবং তারা স্বয়ংক্রিয়ভাবে সংযোগ করার প্রতিশ্রুতি দেয়, আপনাকে প্রতিবার জোড়া লাগার ঝামেলা বাঁচায়। এটা একটা সুন্দর রোম্যান্স।
যতক্ষণ না এটি না হয়।
হঠাৎ একদিন, তারা একে অপরকে ভুলে যায়। সংযোগ চলে গেছে। বিশ্বাস ভেঙ্গে গেছে। এবং আপনার অ্যাপটি মাঝখানে রেখে দেওয়া হয়েছে, থেরাপিস্ট খেলতে চেষ্টা করছেন, কোন ধারণা ছাড়াই কি ভুল হয়েছে। আপনি ভূত হয়েছে. এবং এখন অবধি, অ্যান্ড্রয়েড কোনও সাহায্য করেনি। আপনি একটি বিজ্ঞপ্তি পাবেন যে বন্ডের অবস্থা এখন BOND_NONE, কিন্তু এটাই। কোন ব্যাখ্যা নেই। কোন বন্ধ. শুধুমাত্র একটি ব্যর্থ সংযোগের ঠান্ডা, কঠিন নীরবতা।
অবশেষে, কিছু বন্ধ!
কিন্তু অ্যান্ড্রয়েড টিমের আমাদের বন্ধুরা স্পষ্টতই কিছু কঠিন ব্রেকআপের মধ্য দিয়ে গেছে, কারণ AOSP 16-এ, তারা আমাদের বন্ধ করার উপহার দিয়েছে। BluetoothDevice পেশ করা হচ্ছে৷EXTRA_BOND_LOSS_REASON৷ এটি একটি নতুন অতিরিক্ত যা ACTION_BOND_STATE_CHANGED সম্প্রচারের সাথে আসে এবং বন্ডটি কেন হারিয়েছিল তা এখানে আপনাকে জানানোর জন্য। এটি একটি ব্রেকআপ টেক্সট পাওয়ার মতো যা আসলে কী ঘটেছে তা ব্যাখ্যা করে!
এখন, যখন একটি বন্ড ভেঙ্গে যায়, আপনি একটি নির্দিষ্ট কারণ কোড পেতে পারেন। এগুলোকে ক্লাসিক ব্রেকআপের অজুহাত হিসেবে ভাবুন, কিন্তু ব্লুটুথের জন্য:
কারণ কোড (দৃষ্টান্তমূলক)
এটি আসলে কী বোঝায়
BOND_LOSS_REASON_BREDR_AUTH_FAILURE
নির্দেশ করে যে বন্ড ক্ষতির কারণ হল BREDR প্রমাণীকরণ ব্যর্থতা৷
BOND_LOSS_REASON_BREDR_INCOMING_PAIRING
নির্দেশ করে যে বন্ড ক্ষতির কারণ হল BREDR জোড়া ব্যর্থতা।
BOND_LOSS_REASON_LE_ENCRYPT_FAILURE
নির্দেশ করে যে বন্ড ক্ষতির কারণ হল LE এনক্রিপশন ব্যর্থতা৷
৷BOND_LOSS_REASON_LE_INCOMING_PAIRING
নির্দেশ করে যে বন্ড ক্ষতির কারণ হল LE জোড়া ব্যর্থতা৷
৷কোড:ডিটেকটিভ বাজানো
সুতরাং, কিভাবে আমরা এই সরস গসিপ পেতে পারি? We need to set up a BroadcastReceiver to listen for bond state changes.
// Create a BroadcastReceiver to listen for bond state changes
private val bondStateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action == BluetoothDevice.ACTION_BOND_STATE_CHANGED) {
val device: BluetoothDevice? = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
val bondState = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, BluetoothDevice.ERROR)
val previousBondState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, BluetoothDevice.ERROR)
// Check if we went from bonded to not bonded
if (bondState == BluetoothDevice.BOND_NONE && previousBondState == BluetoothDevice.BOND_BONDED) {
Log.d("BondBreakup", "We got dumped by ${device?.address}!")
// Now, let's find out why...
val reason = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_LOSS_REASON, -1)
when (reason) {
// Note: The actual constant values are in the Android SDK
BluetoothDevice.BOND_LOSS_REASON_REMOTE_DEVICE_REMOVED -> {
Log.d("BondBreakup", "Reason: The remote device removed the bond.")
// You could show a message to the user: "Your headphones seem to have forgotten you. Please try pairing again."
}
// ... handle other reasons ...
else -> {
Log.d("BondBreakup", "Reason: It's complicated (Unknown reason code: $reason)")
}
}
}
}
}
}
// In your Activity or Service, register the receiver
override fun onResume() {
super.onResume()
val filter = IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED)
registerReceiver(bondStateReceiver, filter)
}
override fun onPause() {
super.onPause()
// Don't forget to unregister!
unregisterReceiver(bondStateReceiver)
}
The code above implements a detective system for Bluetooth bond breakups, and it's more sophisticated than it might first appear. Let's walk through how this broadcast receiver pattern works and why it's so powerful.
First, we're creating a BroadcastReceiver , which is Android's way of letting your app listen for system-wide events. Think of it as subscribing to a notification service, whenever something interesting happens in the Android system (like a bond state change), the system broadcasts an "intent" to all registered listeners. Our receiver is one of those listeners.
In the onReceive() method, we first check if the incoming intent's action is ACTION_BOND_STATE_CHANGED . This is crucial because broadcast receivers can potentially receive many different types of intents, and we only care about bond state changes. Once we've confirmed this is the right type of event, we extract the relevant information from the intent using getParcelableExtra() and getIntExtra() .
The device object tells us which Bluetooth device this event is about. After all, you might be bonded to multiple devices (your headphones, your smartwatch, your car), and we need to know which one just broke up with us. The bondState tells us the current state (are we bonded, bonding, or not bonded?), and previousBondState tells us what the state was before this change occurred.
The key logic happens in our conditional check:if (bondState == BluetoothDevice.BOND_NONE && previousBondState == BluetoothDevice.BOND_BONDED) . This is checking for the specific transition from "bonded" to "not bonded," which is the digital equivalent of a breakup. We're not interested in the bonding process itself (going from none to bonding to bonded) – we only care about when an existing bond is lost.
Once we've detected a breakup, we extract the new EXTRA_BOND_LOSS_REASON from the intent. This is the star feature from AOSP 16 that finally gives us closure. The reason code tells us exactly why the bond was lost – was it the remote device that ended things? Did the user manually forget the device? Did authentication fail? Each reason code corresponds to a different scenario, and you can handle each one appropriately.
In the example above, we're using a when expression to handle different reason codes. For BOND_LOSS_REASON_BREDR_INCOMING_PAIRING, we know the other device initiated the breakup, so we can show a helpful message like "Your headphones seem to have forgotten you. Please try pairing again." For other reasons, you'd add more branches to handle them specifically.
Now, notice the lifecycle management at the bottom. We register our receiver in onResume() and unregister it in onPause() . This is critical:if you forget to unregister a broadcast receiver, it will continue to receive broadcasts even after your Activity is destroyed, which can cause memory leaks and crashes. The pattern of registering in onResume() and unregistering in onPause() ensures that we only listen for bond changes when our Activity is visible and active.
This is a huge step forward for debugging and for user experience. Instead of just telling the user "Connection failed," you can now give them actionable advice based on the specific reason the bond was lost. It's like being a helpful, informed relationship counselor instead of a confused bystander who can only shrug and say "I don't know what happened."
Now that we've dealt with the emotional baggage of breakups, let's move on to something a little more lighthearted:speed dating for Bluetooth devices.
Deep Dive #3:Service UUIDs from Advertisements
Let's talk about finding a compatible partner... for your app. In the world of BLE, not all devices are created equal. A heart rate monitor is very different from a smart lightbulb. So how does your app know if it's talking to the right kind of device? The answer is the Service UUID.
What in the World is a Service UUID?
A Service UUID (Universally Unique Identifier) is like a device's job title. It's a unique, 128-bit number that says, "I am a device that provides a Heart Rate Service" or "I am a device that provides a Battery Service." It's the single most important piece of information for determining what a device can do.
The Old Way:The Awkward First Date
Traditionally, finding out a device's services was a whole ordeal. It was like going on a full, three-course dinner date just to find out the other person's job. The process went something like this:
-
Scan:Find the device.
-
Connect:Establish a connection (a slow and power-hungry process).
-
Discover Services:Ask the device, "So... what do you do for a living?" and wait for it to list all its services.
-
Evaluate:Check if the list of services contains the one you're interested in.
-
Disconnect (or stay connected):If it's not the right device, you have to break up (disconnect) and move on. What a waste of time and energy!
This is incredibly inefficient, especially if you're in a crowded room with dozens of BLE devices and you're only looking for one specific type.
The New Way:The Glorious Name Tag
Wouldn't it be great if everyone at a party just wore a name tag with their job title on it? That's exactly what AOSP 16 has given us with BluetoothDevice.EXTRA_UUID_LE. Many BLE devices are already polite enough to include their primary service UUID in their advertisement packets. It's their way of shouting, "I'M A HEART RATE MONITOR!" to the whole room.
Before AOSP 16, getting this information out of the advertisement packet was a messy, manual process of parsing the raw byte array of the scan record. It was doable, but it was the kind of code that you'd write once, pray it worked, and never touch again.
Now, Android does the dirty work for us! The system automatically parses the advertising data and, if it finds any service UUIDs, it conveniently hands them to you in the ScanResult.
The Code:Reading the Name Tag
This new feature makes our ScanCallback even more powerful. We can now check the device's job title the moment we discover it, without ever having to connect.
private val scanCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
Log.d("BleSpeedDating", "Found device: ${result.device.address}")
// Let's check their name tag!
val serviceUuids = result.scanRecord?.serviceUuids
if (serviceUuids.isNullOrEmpty()) {
Log.d("BleSpeedDating", "This one is mysterious. No service UUIDs in the ad.")
return
}
// Define the UUID we're looking for (e.g., the standard Heart Rate Service UUID)
val heartRateServiceUuid = ParcelUuid.fromString("0000180D-0000-1000-8000-00805F9B34FB")
if (serviceUuids.contains(heartRateServiceUuid)) {
Log.d("BleSpeedDating", "It's a match! This is a heart rate monitor. Let's connect!")
// Now you can proceed to connect to result.device, knowing it's the right one.
stopBleScan() // We found what we were looking for
// connectToDevice(result.device)
} else {
Log.d("BleSpeedDating", "Not a match. Moving on.")
}
}
// ... onScanFailed ...
}
The code above demonstrates the power of reading service UUIDs directly from advertisement data, and it's a game-changer for device discovery. Let's break down exactly what's happening and why this is such a significant improvement.
When we receive a scan result in our callback, the result object contains a scanRecord সম্পত্তি This scan record is essentially the raw advertisement packet that the BLE device broadcast into the air.
Before AOSP 16, if you wanted to extract service UUIDs from this data, you'd have to manually parse the byte array, understand the BLE advertisement format, handle different data types, and pray you didn't make an off-by-one error. It was the kind of code that worked once and then you never touched it again out of fear.
Now, with the improvements in AOSP 16, Android does all that messy parsing for us. We can simply call result.scanRecord?.serviceUuids and get back a nice, clean list of ParcelUuid বস্তু The safe call operator (?. ) is important here because not all devices include a scan record in their results, and we need to handle that gracefully.
After retrieving the service UUIDs, we check if the list is null or empty. Some devices don't include service UUIDs in their advertisements. They might be using a proprietary format, or they might just be poorly configured. If there are no UUIDs, we log a message and return early. There's no point in continuing if we can't identify what the device does.
Next, we define the UUID we're looking for. In this example, we're searching for heart rate monitors, so we use the standard Heart Rate Service UUID:0000180D-0000-1000-8000-00805F9B34FB . This is a UUID defined by the Bluetooth SIG (Special Interest Group), and any compliant heart rate monitor will advertise this UUID. You can find a complete list of standard service UUIDs in the Bluetooth specifications, or you can use custom UUIDs if you're building your own BLE peripherals.
The magic happens in the if (serviceUuids.contains(heartRateServiceUuid)) চেক This is where we're doing our speed dating:we're checking the device's "name tag" to see if it matches what we're looking for.
If it does, we've found our match! We can immediately stop scanning (because why keep looking when we've found what we need?) and proceed to connect to the device. We know, with certainty, that this device is a heart rate monitor, so we won't waste time and battery connecting to random devices only to discover they're not what we need.
If the UUID doesn't match, we simply log "Not a match" and move on. The callback will be called again when the next device is found, and we'll repeat this process until we find our heart rate monitor or the user stops the scan.
This is a massive performance improvement over the old approach. Previously, you'd have to connect to every device you found, perform service discovery (which involves multiple round-trip communications with the device), check if it has the services you need, and then disconnect if it doesn't. Each connection attempt takes time, uses battery, and creates unnecessary radio traffic.
Now, you can filter and identify devices at lightning speed, all at the scanning stage. No more awkward first dates where you connect to a smart lightbulb thinking it might be a fitness tracker. Just efficient, targeted connections.
This is particularly useful for apps that need to find a specific type of sensor or peripheral in a sea of irrelevant devices. Imagine you're in a hospital with hundreds of BLE-enabled medical devices, or in a smart home with dozens of sensors and actuators. Being able to instantly identify the right device from its advertisement is the difference between a responsive, professional app and one that feels sluggish and unreliable.
We've now met all three of our Bluetooth musketeers:passive scanning for battery efficiency, bond loss reasons for better debugging, and service UUIDs from advertisements for faster device identification. But our journey isn't over. It's time to venture into the deep woods of advanced scanning techniques.
Advanced Topics:Filtering, Batching, and Other Sorcery
Alright, you've mastered the basics. You can scan passively, you can get closure on your connection breakups, and you can speed-date devices like a pro. You're no longer a Bluetooth padawan. It's time to become a Jedi Master.
Let's dive into the advanced arts of filtering, batching, and other optimization sorcery that will make your app a true battery-saving champion.
Hardware Filtering:Your Personal Assistant
Imagine you're a celebrity, and you've hired a personal assistant. You don't want to be bothered by every single person who wants an autograph. So, you give your assistant a list:"Only let me know if you see my agent or my mom." Your assistant then stands at the door and only bothers you when someone on the list shows up.
This is exactly what hardware filtering does. Instead of your app's code (the celebrity) being woken up for every single Bluetooth device the radio sees, you can offload the filtering logic to the Bluetooth controller itself (the personal assistant). This is a feature that's been around since Android 6.0, but it's more important than ever.
কেন এই এত মহান? Because your app's code can stay asleep. The main processor (the AP) doesn't have to wake up every time a random Bluetooth toothbrush advertises itself. The Bluetooth controller, which is much more power-efficient, handles the filtering. The AP only wakes up when the controller finds a device that matches your criteria.
The Code:Building Your VIP List
You implement this using ScanFilter. You can filter by a device's name, its MAC address, or, most usefully, by the Service UUID it's advertising.
// We only want to be bothered if we see a heart rate monitor.
val heartRateServiceUuid = ParcelUuid.fromString("0000180D-0000-1000-8000-00805F9B34FB")
val filter = ScanFilter.Builder()
.setServiceUuid(heartRateServiceUuid)
.build()
val scanFilters: List<ScanFilter> = listOf(filter)
// Now, when you start your scan, pass in this list
bleScanner.startScan(scanFilters, scanSettings, scanCallback)
The code above shows how to create a hardware-level filter that dramatically improves both battery life and app performance. Let's dive deep into what's happening here and why this is such a powerful technique.
We start by defining the service UUID we're interested in – in this case, the standard Heart Rate Service UUID. This is the same UUID we used in the previous example, but now we're using it in a fundamentally different way. Instead of checking the UUID in our app's code after receiving scan results, we're telling the Bluetooth hardware itself to only report devices that match this UUID.
The ScanFilter.Builder() is our tool for constructing this filter. It's a builder pattern, which means we can chain multiple methods together to configure exactly what we're looking for. In this example, we're calling setServiceUuid(heartRateServiceUuid) , which tells the filter to only match devices that advertise this specific service.
But the builder has many other options you can use:
-
setDeviceName()– Match devices with a specific name (like "My Heart Monitor") -
setDeviceAddress()– Match a specific device by its MAC address (useful if you've already paired with a device and want to find it again) -
setManufacturerData()– Match devices based on manufacturer-specific data in their advertisements -
setServiceData()– Match based on service data included in the advertisement
You can even combine multiple criteria in a single filter. For example, you could create a filter that matches devices with a specific service UUID and a specific manufacturer ID. The more specific your filter, the fewer false positives you'll get.
After building our filter, we create a list containing it. Why a list? Because you can have multiple filters, and a device will match if it satisfies any of the filters in the list. For instance, you might create one filter for heart rate monitors and another for blood pressure monitors, and your scan will report devices that match either one. This is an OR operation:the device doesn't need to match all filters, just one of them.
Finally, we pass this list of filters to startScan() along with our scan settings and callback. এখানেই ম্যাজিক ঘটে। When you provide filters, Android doesn't just filter the results in your app's code. It pushes these filters down to the Bluetooth controller hardware itself. This means the filtering happens at the lowest level, before your app is even notified.
Here's why this is so powerful:without filters, every time the Bluetooth radio hears an advertisement from any device (your neighbor's smart toaster, someone's fitness tracker walking by, the Bluetooth speaker three rooms away), it has to wake up your app's process, deliver the scan result, and let your code decide if it cares about this device. Each of these wake-ups costs battery and processing time.
With hardware filters, the Bluetooth controller silently ignores all the devices that don't match your criteria. Your app stays asleep. The main processor stays asleep. Only when a heart rate monitor is detected does the hardware wake up your app and deliver the result. It's like having a bouncer at a club who only lets in people on the VIP list. Everyone else is turned away at the door, and you never even know they were there.
By using a ScanFilter , you're telling the hardware, "Don't wake me up unless you see a heart rate monitor." It's the ultimate power-saving move for background scanning. Combined with passive scanning and batch reporting, you can create a Bluetooth scanning system that runs for hours or even days with minimal battery impact. This is how professional-grade apps handle long-term device monitoring without destroying battery life.
Batch Scanning:The Daily Report
Let's go back to our celebrity analogy. Sometimes, you don't need to be interrupted the moment your mom shows up. You'd rather just get a report at the end of the day:"Today, your mom stopped by twice, and your agent called once." This is batch scanning.
Instead of delivering scan results to your app in real-time, the Bluetooth controller can collect them and deliver them in a big batch. This is another incredible power-saving feature. Your app can sleep for long periods, then wake up, process a whole bunch of results at once, and go back to sleep.
You enable this with the setReportDelay() method in your ScanSettings.
val scanSettings = ScanSettings.Builder()
// ... other settings ...
// Deliver results every 5 seconds (5000 milliseconds)
.setReportDelay(5000)
.build()
When you use a report delay, your onScanResult callback will be replaced by onBatchScanResults, which gives you a List
private val scanCallback = object : ScanCallback() {
override fun onBatchScanResults(results: List<ScanResult>) {
Log.d("BatchScanner", "Here's your daily report! Found ${results.size} devices.")
for (result in results) {
// Process each result
}
}
// ... onScanFailed ...
}
The batch scanning mechanism shown above is one of the most underutilized power-saving features in Android Bluetooth, and understanding how it works can transform your app's battery profile. Let's break down exactly what's happening under the hood and when you should use this technique.
When you set a report delay of 5000 milliseconds (5 seconds) in the code above, you're fundamentally changing how the scanning pipeline works. Instead of the Bluetooth controller immediately waking up your app every time it sees a device, it acts like a diligent assistant taking notes. For those 5 seconds, the controller silently collects every scan result it encounters, storing them in its own internal buffer. Your app remains completely asleep during this time – no CPU cycles wasted, no battery drained by context switches or process wake-ups.
After the 5-second delay expires, the controller delivers all the accumulated results in one batch to your onBatchScanResults() callback. This is where the power savings come from:instead of waking up your app 50 times if 50 devices were detected, it wakes up once and hands you all 50 results at the same time. Your app can then efficiently process this batch – maybe updating a UI list, logging the data, or checking for specific devices – and then go back to sleep until the next batch arrives.
The results parameter in onBatchScanResults() is a List<ScanResult> , and each ScanResult in the list represents a single advertisement that was heard during the batching period. It's important to note that if the same device advertises multiple times during the delay period, you might receive multiple results for that device in the batch. The list isn't automatically deduplicated – that's your job if you need it.
In the example above, we're simply logging the number of devices found and then iterating through each result. In a real application, you might want to do more sophisticated processing. For instance, you could build a map of devices keyed by MAC address to track how many times each device advertised, calculate average RSSI values to estimate distance, or filter the batch to only process devices that meet certain criteria.
সতর্কতা: Batch scanning is a powerful tool, but it's not for every situation. If you need to react to a device's presence immediately (for example, if you're building a "find my keys" app where the user is actively searching), a report delay is not your friend. The user doesn't want to wait 5 seconds to see results – they want instant feedback. In these cases, set setReportDelay(0) for immediate reporting.
But for long-term monitoring or data collection scenarios, batch scanning is a battery's best friend. Consider these use cases:
-
Background presence monitoring :Your app checks every minute to see if the user's smartwatch is still in range, but doesn't need second-by-second updates.
-
Environmental sensing :You're collecting data from temperature sensors throughout a building and only need to update your dashboard every 30 seconds.
-
Beacon analytics :You're tracking how many people pass by a retail location based on their phone's BLE advertisements, and you aggregate the data every 10 seconds.
The sweet spot for report delay depends on your use case. Too short (like 1 second), and you're not getting much benefit, you're still waking up frequently. Too long (like 60 seconds), and your app might feel unresponsive or miss time-sensitive events. For most background monitoring tasks, delays between 5 and 30 seconds work well.
One more thing to be aware of:batch scanning has limits. The Bluetooth controller has a finite buffer for storing scan results. If you set a very long delay and you're in an environment with hundreds of BLE devices, the buffer might fill up before the delay expires. When this happens, the oldest results get dropped. Android doesn't give you a warning when this occurs, so if you're missing data, consider reducing your report delay or using more aggressive filters to reduce the number of results being collected.
OnFound/OnLost:The Drama of Presence
Since Android 8.0, scanning has gotten even more dramatic. You can now ask the hardware to not only tell you when it finds a device, but also when it loses one. This is done using the CALLBACK_TYPE_FIRST_MATCH and CALLBACK_TYPE_MATCH_LOST flags in your ScanSettings.
val scanSettings = ScanSettings.Builder()
.setCallbackType(ScanSettings.CALLBACK_TYPE_FIRST_MATCH or ScanSettings.CALLBACK_TYPE_MATCH_LOST)
.build()
Now, in your ScanCallback, the callbackType parameter in onScanResult will tell you what happened.
override fun onScanResult(callbackType: Int, result: ScanResult) {
when (callbackType) {
ScanSettings.CALLBACK_TYPE_FIRST_MATCH -> {
Log.d("PresenceDetector", "Found them! ${result.device.address} has entered the building.")
}
ScanSettings.CALLBACK_TYPE_MATCH_LOST -> {
Log.d("PresenceDetector", "They're gone! ${result.device.address} has left the building.")
}
}
}
The presence detection mechanism shown above represents a fundamental shift in how we think about Bluetooth scanning. Instead of treating scanning as a continuous stream of "here's what I see right now," we're now working with events:"this device appeared" and "this device disappeared." Let's dive deep into how this works and why it's so powerful.
When you set the callback type using the bitwise OR operator (or in Kotlin, | in Java), you're telling the Bluetooth hardware to track the presence state of devices over time. The code CALLBACK_TYPE_FIRST_MATCH or CALLBACK_TYPE_MATCH_LOST combines both flags, meaning you want to be notified both when a device first appears and when it disappears. You can use these flags individually if you only care about one type of event, but using both together gives you complete presence awareness.
Let's understand what "first match" and "match lost" actually mean. When the Bluetooth controller hears an advertisement from a device that matches your filters for the first time, it triggers a CALLBACK_TYPE_FIRST_MATCH ঘটনা This is different from CALLBACK_TYPE_ALL_MATCHES (the default), which would trigger every single time the device advertises. A device might advertise multiple times per second, so the difference is significant. With FIRST_MATCH , you get one notification when the device enters your scanning range, not a flood of notifications as it continues to advertise.
The CALLBACK_TYPE_MATCH_LOST event is even more interesting. The Bluetooth controller keeps track of when it last heard from each device. If a device stops advertising (because it moved out of range, was turned off, or its battery died), the controller notices the absence and triggers a MATCH_LOST ঘটনা This happens automatically:you don't have to manually track timestamps or implement timeout logic in your app. The hardware does it for you.
But how does the hardware know when a device is "lost"? It uses an internal timeout. If the controller hasn't heard from a device for a certain period (typically a few seconds, though the exact duration is implementation-dependent and not exposed to apps), it considers the device lost. This means there's a slight delay between when a device actually leaves range and when you get the MATCH_LOST callback, but this delay is usually acceptable for presence detection use cases.
In the code example above, we're using a when expression to handle the different callback types. When we receive a FIRST_MATCH , we know the device has just entered our scanning range, so we log "Found them!" This is perfect for triggering actions like unlocking a door when your phone comes near, or starting to sync data when your fitness tracker is detected.
When we receive a MATCH_LOST , we know the device has left our scanning range or stopped advertising, so we log "They're gone!" This is ideal for triggering cleanup actions like locking the door when your phone leaves, or stopping a data sync when your tracker disconnects.
This is incredibly useful for presence detection scenarios. Is your smart lock in range? Is your fitness tracker still connected? Is the user's phone nearby? Now you can know, with hardware-level certainty, and you can react to changes in presence without constantly polling or maintaining complex state machines in your app code.
Here's a practical example of how you might use this in a smart home app:
private val presenceCallback = object : ScanCallback() {
override fun onScanResult(callbackType: Int, result: ScanResult) {
when (callbackType) {
ScanSettings.CALLBACK_TYPE_FIRST_MATCH -> {
// User's phone detected - they're home!
Log.d("SmartHome", "Welcome home! Unlocking door and turning on lights.")
unlockFrontDoor()
turnOnLights()
adjustThermostat(COMFORTABLE_TEMP)
}
ScanSettings.CALLBACK_TYPE_MATCH_LOST -> {
// User's phone is gone - they left!
Log.d("SmartHome", "Goodbye! Locking door and entering away mode.")
lockFrontDoor()
turnOffLights()
adjustThermostat(ENERGY_SAVING_TEMP)
armSecuritySystem()
}
}
}
override fun onScanFailed(errorCode: Int) {
Log.e("SmartHome", "Presence detection failed: $errorCode")
}
}
One important consideration:FIRST_MATCH and MATCH_LOST are mutually exclusive with CALLBACK_TYPE_ALL_MATCHES . If you combine them with ALL_MATCHES , the behavior becomes undefined and varies by device. Stick to either ALL_MATCHES for continuous reporting, or FIRST_MATCH /MATCH_LOST for presence detection – don't try to use both at once.
Also, be aware that presence detection works best when combined with hardware filtering. If you're scanning for all devices without filters, the controller has to track the presence state of every single BLE device in range, which can overwhelm its internal tracking tables. Always use ScanFilter to narrow down which devices you care about when using presence detection.
By combining these advanced techniques – hardware filtering, batch scanning, and presence detection – you can build incredibly sophisticated and power-efficient Bluetooth applications. You're not just a developer anymore. You're a Bluetooth wizard, wielding the power to create apps that are aware of their surroundings, responsive to changes, and respectful of battery life.
Now, let's see where we can apply these magical powers in the real world.
Real-World Use Cases:Where the Bluetooth Hits the Road
Okay, we've learned a ton of cool new tricks. We're basically Bluetooth black belts at this point. But what's the use of all this power if we don't use it for good (or at least for a cool app)? Let's explore some real-world scenarios where the new features in AOSP 16 can turn a good app into a great one.
1. The "Find My Everything" App
আমরা সব সেখানে হয়েছে. You're late for work, and your keys have decided to play a game of hide-and-seek in another dimension. This is the classic use case for a BLE tracker.
-
The Old Way: Your app would be constantly doing active scans, draining your battery while you frantically search. It would connect to every tracker in your house just to see if it's the right one.
-
The AOSP 16 Way: Your app runs a passive scan in the background with a hardware filter for your tracker's specific Service UUID. The battery impact is minimal. When you open the app to find your keys, it already knows they're in the house because it's been listening silently. You hit the "Find" button, the app connects, and your keys start screaming from inside the couch cushions. And if the connection fails? Bond loss reason tells you if the tracker's battery died, so you're not looking for a dead device.
2. The Smart Supermarket
Imagine an app that gives you coupons for products as you walk past them in the store. This is the dream of proximity marketing, a dream that has been historically thwarted by, you guessed it, battery drain.
-
The Old Way: The app would need to constantly scan for beacons, turning the user's phone into a hot potato and a dead battery by the time they reach the checkout line.
-
The AOSP 16 Way: The supermarket places BLE beacons in each aisle. Your app uses a passive, batched scan. It wakes up every minute or so, gets a list of all the beacons it has seen, and then goes back to sleep. When it sees you've been loitering in the cookie aisle for five minutes (it knows, it always knows), it uses the Service UUID from the advertisement to identify the "Cookie Aisle Beacon" and sends you a coupon for Oreos. It's targeted, it's efficient, and it doesn't kill your battery before you can pay.
3. The Overly-Attached Smart Home
Your smart home should be, well, smart. It should know when you're home and when you've left. It should lock the door behind you and turn on the lights when you arrive.
-
The Old Way: You'd have to rely on GPS (a notorious battery hog) or Wi-Fi connections, which can be unreliable. BLE was an option, but constant scanning was a problem.
-
The AOSP 16 Way: Your phone is the key. Your smart hub (acting as a central device) runs a continuous, low-power passive scan. When it sees your phone's BLE advertisement, it knows you're home. But what if you just walk by the house? This is where the OnFound/OnLost feature comes in. The hub can be configured to only trigger the "Welcome Home" sequence after it has seen your device consistently for a minute (OnFound), and to trigger the "Goodbye" sequence only after it hasn't seen you for five minutes (OnLost). It's a smarter, more reliable presence detection system that finally makes the smart home feel... smart.
4. The Corporate Asset Tracker
In a large hospital or warehouse, keeping track of expensive, mobile equipment (like IV pumps or forklifts) is a huge challenge. BLE tags are the solution.
-
The Old Way: Employees would have to walk around with a tablet, doing active scans to take inventory. It's slow, manual, and inefficient.
-
The AOSP 16 Way: A network of fixed BLE gateways is installed throughout the building. Each gateway is a simple device (like a Raspberry Pi) running a continuous passive scan. They collect all the advertisement data from the asset tags and send it to a central server. The server can now see, in real-time, that IV Pump #34 is in Room 201, and Forklift #3 is currently in the loading bay. No manual scanning required. It's a low-cost, low-power, real-time location system, all thanks to the efficiency of passive scanning.
এগুলো মাত্র কয়েকটি উদাহরণ। From fitness trackers to industrial sensors, the new Bluetooth features in AOSP 16 open up a world of possibilities for building apps that are not only powerful but also polite to your user's battery. Now, let's talk about how to make sure our shiny new app works on all devices, not just the new ones.
API Version Checking:How to Not Crash Your App
So, you've built a beautiful, battery-sipping app using all the new hotness from AOSP 16's Q4 release. You're ready to ship it, become a millionaire, and retire to a private island. But then, a bug report comes in. Your app is crashing on a brand new Android 16 device. What gives?!
Welcome, my friend, to the wonderful world of API version checking. With Android's new release schedule, this has become more important (and slightly more complicated) than ever.
The Problem:A Tale of Two Android 16s
As we discussed, 2025 gave us two Android 16 releases:
-
The Q2 Release: The main "Baklava" release. Let's call this API level 36.0.
-
The Q4 Release: The minor, feature-drop release. This is where our new Bluetooth toys live. Let's call this API level 36.1.
Our new passive scanning API, setScanType(), only exists on 36.1 and later. If you try to call it on a device that's running the initial Q2 release (36.0), your app will crash with a NoSuchMethodError. It's the digital equivalent of asking for a menu item that was only added last night. The chef (your app) just gets confused and has a meltdown.
The Old Guard:SDK_INT
For years, our trusty friend for checking API levels has been Build.VERSION.SDK_INT. It's simple and effective.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
// Use an API from Android 12 (S) or higher
}
But SDK_INT only knows about major releases. For both Android 16 Q2 and Q4, SDK_INT will just report 36. It has no idea about the minor version. It's like asking someone their age, and they just say "thirties." Not very specific.
The New Hotness:SDK_INT_FULL
To solve this, the Android team has given us a new, more precise tool:Build.VERSION.SDK_INT_FULL . This constant knows about both the major and minor version numbers. And to go with it, we have a new set of version codes:Build.VERSION_CODES_FULL .
So, to safely call our new passive scanning API, we need to do a more specific check:
// Let's build our ScanSettings
val scanSettingsBuilder = ScanSettings.Builder()
.setScanMode(ScanSettings.SCAN_MODE_LOW_POWER)
// Now, let's check if we can go passive
if (Build.VERSION.SDK_INT_FULL >= Build.VERSION_CODES_FULL.BAKLAVA_1) {
Log.d("ApiCheck", "This device is cool. Going passive.")
// This is the new API from the Q4 release (36.1)
scanSettingsBuilder.setScanType(ScanSettings.SCAN_TYPE_PASSIVE)
} else {
Log.d("ApiCheck", "This device is old school. Sticking to active scanning.")
// Fallback for devices that don't have the new API
// We don't need to do anything here, as active is the default
}
val scanSettings = scanSettingsBuilder.build()
Graceful Degradation:The Art of Falling with Style
This brings us to a crucial concept:graceful degradation. It means your app should still work on older devices, even if it can't use the latest and greatest features. It should fall back gracefully.
In our example above, if the setScanType method isn't available, we just... don't call it. The app will default to a normal, active scan. It won't be as battery-efficient, but it will still work. The user on the older device gets a functional app, and the user on the newer device gets a more optimized experience. Everybody wins.
Here's a table to help you remember when to use which check:
If you're using an API from...
Use this check...
A major Android release (for example, Android 16 Q2)
if (SDK_INT>=VERSION_CODES.BAKLAVA)
A minor, feature-drop release (for example, Android 16 Q4)
if (SDK_INT_FULL>=VERSION_CODES_FULL.BAKLAVA_1)
Mastering this new API checking is non-negotiable. It's the key to writing modern Android apps that are both innovative and stable. Now that we know how to build a robust app, let's talk about how to fix it when it inevitably breaks.
Testing and Debugging:The Fun Part (Said No One Ever)
There are two universal truths in software development:
-
It works on my machine, and
-
It will break in the most spectacular way possible during a live demo.
Bluetooth development, in particular, seems to delight in this second truth. It's a fickle, invisible force that seems to have a personal vendetta against developers.
So, how do we fight back? With a solid testing and debugging strategy. It's not glamorous, but it's the only way to stay sane.
The Emulator:A Land of Make-Believe
Android Studio's emulator is a fantastic tool. It's fast, it's convenient, and it can simulate all sorts of devices. And for Bluetooth? It can... sort of help. The emulator does have virtual Bluetooth support. You can enable it, and your app will think it has a Bluetooth adapter. It's great for testing your UI and making sure your app doesn't crash when it tries to get the BluetoothLeScanner.
But here's the catch:it's not real. The emulator can't actually interact with the radio waves in your room. You can't use it to find your real-life BLE headphones. For that, you need to venture into the real world.
The Real World:Where the Bugs Live
There is no substitute for testing on real, physical devices. Every phone manufacturer has its own special flavor of Bluetooth stack, its own quirky antenna design, and its own unique way of making your life difficult. A scan that works perfectly on a Google Pixel might fail miserably on another brand. The only way to know is to test.
Your testing arsenal should include:
-
A variety of phones: Different brands, different Android versions. The more, the better.
-
A variety of BLE peripherals: Don't just test with one type of device. Get a few different beacons, sensors, or wearables. You'll be amazed at how differently they behave.
Common Errors:The Usual Suspects
When your scan inevitably fails, it will give you an error code. Here are a few of the most common culprits:
Error Code
The Problem
How to Fix It
SCAN_FAILED_ALREADY_STARTED
You tried to start a scan that was already running.
You got too excited. Make sure you're not calling startScan() multiple times without calling stopScan() in between.
SCAN_FAILED_APPLICATION_REGISTRATION_FAILED
Something is fundamentally wrong with your app's setup.
This is a vague and unhelpful error. It usually means you have a problem with your permissions or the system is just having a bad day. Try restarting Bluetooth.
SCAN_FAILED_INTERNAL_ERROR
The Bluetooth stack had a panic attack.
This is the classic "it's not you, it's me" error. It's an internal issue with the device's Bluetooth controller. There's not much you can do except try again later.
SCAN_FAILED_FEATURE_UNSUPPORTED
You tried to use a feature the hardware doesn't support.
You might be trying to use batch scanning on a device that doesn't support it. Use your API version checks!
Debugging Tools:Your Ghost-Hunting Kit
When things go wrong, you need the right tools to see what's happening in the invisible world of Bluetooth.
-
logcat: এটি আপনার সেরা বন্ধু। Be generous with your log statements. Log when you start a scan, when you stop a scan, when you find a device, and when a scan fails. Create a filter for your app's tag so you can see the signal through the noise.
-
Android's Bluetooth HCI Snoop Log: This is the holy grail of Bluetooth debugging. It's a developer option that records every single Bluetooth packet that goes in or out of your device. It's incredibly detailed and can be overwhelming, but it's the ultimate source of truth. You can open the generated log file in a tool like Wireshark to see the raw, unfiltered conversation between your phone and the BLE device. It's like having a wiretap on the radio waves.
-
nRF Connect for Mobile: This is a free app from Nordic Semiconductor, and it's an essential tool for any BLE developer. It lets you scan for devices, see their advertising data, connect to them, and explore their GATT services. If your app can't find a device, the first thing you should do is see if nRF Connect can. If it can't, the problem is likely with the peripheral, not your app.
Testing and debugging Bluetooth is a marathon, not a sprint. It requires patience, a methodical approach, and a healthy dose of self-deprecating humor. But with the right tools and techniques, you can tame the beast.
Now, let's talk about how to make sure our well-behaved app is also a good citizen when it comes to performance.
Performance and Best Practices:How to Be a Good Bluetooth Citizen
Writing code that works is one thing. Writing code that works well, is efficient, and doesn't make your users want to throw their phone against a wall is another thing entirely. When it comes to Bluetooth, being a good citizen is all about one thing:battery, battery, battery.
The Bluetooth radio is a powerful piece of hardware, but it's also a thirsty one. Every moment it's active, it's sipping power. Your job is to make sure it's only sipping when absolutely necessary. Here are the golden rules of being a good Bluetooth citizen.
1. Don't Scan If You Don't Have To
This sounds obvious, but it's the most common mistake. Before you even think about starting a scan, ask yourself:"Do I really need to do this right now?" If the user is not on the screen that needs scan results, don't scan. If the app is in the background, be extra critical. Background scanning is a huge drain on battery and is heavily restricted by Android for that very reason.
2. Stop Your Scan!
I'm going to say it again because it's that important:always stop your scan when you're done. A scan that's left running is like a leaky faucet for your battery. It will drain and drain until there's nothing left. The best practice is to tie your scan lifecycle to your UI lifecycle.
override fun onPause() {
super.onPause()
// The user can't see the screen, so they don't need the results.
stopBleScan()
}
override fun onResume() {
super.onResume()
// The user is back on the screen, let's start scanning again.
startBleScan()
}
If you find the device you're looking for, stop the scan immediately. There's no need to keep looking.
3. Choose the Right Scan Mode
ScanSettings gives you a few different modes. Choose wisely.
-
SCAN_MODE_LOW_POWER: This is your default, everyday mode. It scans in intervals, balancing discovery speed and battery life. Use this for most foreground scanning.
-
SCAN_MODE_BALANCED: একটা মাঝামাঝি জায়গা। It scans more frequently than low power mode.
-
SCAN_MODE_LOW_LATENCY: This is the "I need to find it NOW" mode. It scans continuously. This will find devices the fastest, but it will also drain your battery the fastest. Only use this for short, critical operations.
-
SCAN_MODE_OPPORTUNISTIC: This is the ultimate passive mode. Your app doesn't trigger a scan at all. It just gets results if another app happens to be scanning. It uses zero extra battery, but you have no guarantee of getting results. Use this for non-critical background updates.
And of course, if you're on AOSP 16 QPR2 or later, use setScanType(SCAN_TYPE_PASSIVE) whenever you don't need the scan response data. It's the new king of power efficiency.
4. Use Hardware Filtering and Batching
We covered this in the advanced section, but it's a best practice that's worth repeating. If you're looking for a specific device, use a ScanFilter. If you're doing a long-running scan, use setReportDelay() to batch your results. These two techniques offload the work to the power-efficient Bluetooth controller and let your app's code sleep, which is the number one way to save battery.
5. Be Mindful of Memory
Every ScanResult object that your app receives takes up memory. If you're in a crowded area with hundreds of BLE devices, and you're not using filters, your app can quickly get overwhelmed and run out of memory. This is another reason why filtering is so important. Only get the results you actually care about.
By following these rules, you can build a Bluetooth app that is not only powerful and feature-rich but also respectful of your user's device. You'll be a true Bluetooth sensei. Now, let's wrap things up and look to the future.
Conclusion:The Future is Passive (and That's Okay)
We've been on quite a journey, haven't we? We've traveled back in time to the dark ages of Classic Bluetooth, witnessed the renaissance of BLE, and emerged into the brave new world of AOSP 16. We've learned to be silent ninjas with passive scanning, played detective with bond loss reasons, and mastered the art of speed dating with service UUIDs from advertisements.
If there's one big takeaway from all of this, it's that the future of Bluetooth on Android is smarter, more efficient, and a whole lot less frustrating. The Android team is clearly listening to the pain points of developers and giving us the tools we need to build better, more battery-friendly apps. The introduction of passive scanning isn't just a new feature – it's a change in philosophy. It's an acknowledgment that sometimes, the best way to communicate is to just listen.
As developers, these new tools empower us to move beyond the simple "connect and stream" use cases. We can now build sophisticated, context-aware applications that are constantly aware of their surroundings without turning our users' phones into expensive paperweights. The dream of a truly smart, seamlessly connected world is a little bit closer, and it's going to be built on the back of these power-efficient technologies.
তাই, পরবর্তী কি? The world of Bluetooth is always evolving. We have Bluetooth 5.4 with Auracast, mesh networking, and even more precise location-finding on the horizon. The one thing we can be sure of is that the tools will continue to get better, and the challenges will continue to get more interesting.
For now, take a moment to appreciate the progress we've made. The next time you start a Bluetooth scan and it just works, take a moment to thank the hardworking engineers who made it possible. And the next time your app's battery graph is a beautiful, flat line instead of a terrifying ski slope, give a little nod to the power of passive scanning.
The Bluetooth beast may never be fully tamed, but with AOSP 16, we've been given a much stronger leash. Now go forth and build amazing things. And for the love of all that is holy, remember to stop your scan.
বিনামূল্যে কোড শিখুন. freeCodeCamp-এর ওপেন সোর্স পাঠ্যক্রম 40,000-এরও বেশি লোককে ডেভেলপার হিসেবে চাকরি পেতে সাহায্য করেছে। শুরু করুন