साथी डिवाइस से जोड़ें

Android 8.0 (एपीआई लेवल 26) और इसके बाद के वर्शन वाले डिवाइसों पर, साथी डिवाइस दूसरे डिवाइस से जोड़ने की सुविधा, आपके डिवाइस की ओर से आस-पास मौजूद डिवाइसों के ब्लूटूथ या वाई-फ़ाई से स्कैन करती है ऐप्लिकेशन को डाउनलोड करने के लिए ACCESS_FINE_LOCATION अनुमति. इससे उपयोगकर्ता की निजता सुरक्षा को ज़्यादा से ज़्यादा बढ़ाने में मदद मिलती है. इस तरीके का इस्तेमाल कंपैनियन डिवाइस का शुरुआती कॉन्फ़िगरेशन करें, जैसे कि BLE-capable स्मार्टवॉच. इसके अलावा, साथी डिवाइस को जोड़ने के लिए, जगह की जानकारी वाली सेटिंग चालू होनी चाहिए चालू होना चाहिए.

साथी डिवाइस से जोड़ने की सुविधा न तो अपने-आप कनेक्शन बनाती है और न ही चालू करती है जिसे लगातार स्कैन किया जा रहा है. ऐप्लिकेशन इन कामों के लिए ब्लूटूथ या वाई-फ़ाई कनेक्टिविटी एपीआई का इस्तेमाल कर सकते हैं कनेक्शन बनाएं.

डिवाइस जुड़ जाने के बाद, डिवाइस REQUEST_COMPANION_RUN_IN_BACKGROUND और REQUEST_COMPANION_USE_DATA_IN_BACKGROUND अनुमतियां दी हैं, ताकि ऐप्लिकेशन को बैकग्राउंड से चालू किया जा सके. ऐप्लिकेशन, REQUEST_COMPANION_START_FOREGROUND_SERVICES_FROM_BACKGROUND बैकग्राउंड से फ़ोरग्राउंड सेवा शुरू करने की अनुमति दें.

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

साथी डिवाइस से जोड़ने की सुविधा लागू करें

इस सेक्शन में बताया गया है कि अपनेCompanionDeviceManager ब्लूटूथ, BLE, और वाई-फ़ाई पर साथी डिवाइस के साथ ऐप्लिकेशन डाउनलोड करें.

कंपैनियन डिवाइस के बारे में जानकारी दें

नीचे दिया गया कोड सैंपल, <uses-feature> ने मेनिफ़ेस्ट फ़ाइल में सेव किया जाएगा. इससे सिस्टम को पता चलता है कि आपके ऐप्लिकेशन को कंपैनियन मोड सेट अप करना है डिवाइस.

<uses-feature android:name="android.software.companion_device_setup"/>

DeviceFilter के हिसाब से डिवाइसों की सूची बनाएं

आप रेंज में मौजूद वे सभी कंपैनियन डिवाइस दिखाए जा सकते हैं जो इनसे मेल खाते हों DeviceFilter (पहली इमेज में दिखाया गया है). अगर आपको स्कैन करने के लिए सिर्फ़ एक विकल्प को चुनना है डिवाइस, आप कर सकते हैं setSingleDevice() पाने के लिए true (इमेज 2 में दिखाया गया है).

साथी डिवाइस से जोड़ा जा रहा है
पहली इमेज. साथी डिवाइस से जोड़ा जा रहा है
एक डिवाइस से दूसरे डिवाइस से जोड़ना
दूसरी इमेज. एक डिवाइस से दूसरे डिवाइस से जोड़ना

DeviceFilter की ये सब-क्लास हैं इसे AssociationRequest में बताया जा सकता है:

तीनों सब-क्लास में ऐसे बिल्डर हैं जो फ़िल्टर के कॉन्फ़िगरेशन को आसान बनाते हैं. नीचे दिए गए उदाहरण में, डिवाइस ऐसे ब्लूटूथ डिवाइस को स्कैन करता है जिसमें BluetoothDeviceFilter.

Kotlin

val deviceFilter: BluetoothDeviceFilter = BluetoothDeviceFilter.Builder()
        // Match only Bluetooth devices whose name matches the pattern.
        .setNamePattern(Pattern.compile("My device"))
        // Match only Bluetooth devices whose service UUID matches this pattern.
        .addServiceUuid(ParcelUuid(UUID(0x123abcL, -1L)), null)
        .build()

Java

BluetoothDeviceFilter deviceFilter = new BluetoothDeviceFilter.Builder()
        // Match only Bluetooth devices whose name matches the pattern.
        .setNamePattern(Pattern.compile("My device"))
        // Match only Bluetooth devices whose service UUID matches this pattern.
        .addServiceUuid(new ParcelUuid(new UUID(0x123abcL, -1L)), null)
        .build();

DeviceFilter को AssociationRequest पर सेट करें CompanionDeviceManager यह तय कर सकता है कि किस तरह के डिवाइसों को सीक करना है.

Kotlin

val pairingRequest: AssociationRequest = AssociationRequest.Builder()
        // Find only devices that match this request filter.
        .addDeviceFilter(deviceFilter)
        // Stop scanning as soon as one device matching the filter is found.
        .setSingleDevice(true)
        .build()

Java

AssociationRequest pairingRequest = new AssociationRequest.Builder()
        // Find only devices that match this request filter.
        .addDeviceFilter(deviceFilter)
        // Stop scanning as soon as one device matching the filter is found.
        .setSingleDevice(true)
        .build();

अपना ऐप्लिकेशन AssociationRequest शुरू करने के बाद, associate() CompanionDeviceManager पर फ़ंक्शन का इस्तेमाल करें. associate() फ़ंक्शन AssociationRequest और Callback में लेता है.

Callback IntentSender onAssociationPending जब CompanionDeviceManager किसी डिवाइस का पता लगाता है और उपयोगकर्ता की सहमति वाला डायलॉग लॉन्च किया जा सकता है. उपयोगकर्ता की ओर से डिवाइस की पुष्टि किए जाने के बाद, AssociationInfo डिवाइस का प्रतिशत onAssociationCreated में लौटाया जाता है. अगर आपके ऐप्लिकेशन को कोई डिवाइस नहीं मिलता है, तो कॉलबैक onFailure दिखाता है को गड़बड़ी का मैसेज दिखेगा.

Android 13 (एपीआई लेवल 33) और उसके बाद के वर्शन वाले डिवाइसों पर:

Kotlin

val deviceManager =
  requireContext().getSystemService(Context.COMPANION_DEVICE_SERVICE)

val executor: Executor =  Executor { it.run() }

deviceManager.associate(pairingRequest,
    executor,
    object : CompanionDeviceManager.Callback() {
    // Called when a device is found. Launch the IntentSender so the user
    // can select the device they want to pair with.
    override fun onAssociationPending(intentSender: IntentSender) {
        intentSender?.let {
             startIntentSenderForResult(it, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
        }
    }

    override fun onAssociationCreated(associationInfo: AssociationInfo) {
        // An association is created.
    }

    override fun onFailure(errorMessage: CharSequence?) {
        // To handle the failure.
     }
})

Java

CompanionDeviceManager deviceManager =
        (CompanionDeviceManager) getSystemService(Context.COMPANION_DEVICE_SERVICE);

Executor executor = new Executor() {
            @Override
            public void execute(Runnable runnable) {
                runnable.run();
            }
        };
deviceManager.associate(pairingRequest, new CompanionDeviceManager.Callback() {
    executor,
    // Called when a device is found. Launch the IntentSender so the user can
    // select the device they want to pair with.
    @Override
    public void onDeviceFound(IntentSender chooserLauncher) {
        try {
            startIntentSenderForResult(
                    chooserLauncher, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0
            );
        } catch (IntentSender.SendIntentException e) {
            Log.e("MainActivity", "Failed to send intent");
        }
    }

    @Override
    public void onAssociationCreated(AssociationInfo associationInfo) {
        // An association is created.
    }

    @Override
    public void onFailure(CharSequence errorMessage) {
        // To handle the failure.
    });

Android 12L (एपीआई लेवल 32) या इससे पहले के वर्शन वाले डिवाइसों पर (अब सेवा में नहीं है):

Kotlin

val deviceManager =
      requireContext().getSystemService(Context.COMPANION_DEVICE_SERVICE)

deviceManager.associate(pairingRequest,
    object : CompanionDeviceManager.Callback() {
        // Called when a device is found. Launch the IntentSender so the user
        // can select the device they want to pair with.
        override fun onDeviceFound(chooserLauncher: IntentSender) {
            startIntentSenderForResult(chooserLauncher,
                SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
        }

        override fun onFailure(error: CharSequence?) {
            // To handle the failure.
        }
    }, null)

Java

CompanionDeviceManager deviceManager =
        (CompanionDeviceManager) getSystemService(Context.COMPANION_DEVICE_SERVICE);
deviceManager.associate(pairingRequest, new CompanionDeviceManager.Callback() {
    // Called when a device is found. Launch the IntentSender so the user can
    // select the device they want to pair with.
    @Override
    public void onDeviceFound(IntentSender chooserLauncher) {
        try {
            startIntentSenderForResult(
                    chooserLauncher, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0
            );
        } catch (IntentSender.SendIntentException e) {
            Log.e("MainActivity", "Failed to send intent");
        }
    }

    @Override
    public void onFailure(CharSequence error) {
        // To handle the failure.
    }
}, null);

उपयोगकर्ता को चुनने के नतीजे को वापस फ़्रैगमेंट में भेजा जाता है: onActivityResult() को ध्यान में रखें. इसके बाद, चुने गए डिवाइस को ऐक्सेस किया जा सकता है.

जब उपयोगकर्ता किसी ब्लूटूथ डिवाइस को चुनता है, तो BluetoothDevice. जब उपयोगकर्ता किसी ब्लूटूथ LE डिवाइस को चुनता है, तो android.bluetooth.le.ScanResult. जब उपयोगकर्ता किसी वाई-फ़ाई डिवाइस को चुनता है, तो android.net.wifi.ScanResult.

Kotlin

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    when (requestCode) {
        SELECT_DEVICE_REQUEST_CODE -> when(resultCode) {
            Activity.RESULT_OK -> {
                // The user chose to pair the app with a Bluetooth device.
                val deviceToPair: BluetoothDevice? =
data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)
                deviceToPair?.let { device ->
                    device.createBond()
                    // Continue to interact with the paired device.
                }
            }
        }
        else -> super.onActivityResult(requestCode, resultCode, data)
    }
}

Java

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    if (resultCode != Activity.RESULT_OK) {
        return;
    }
    if (requestCode == SELECT_DEVICE_REQUEST_CODE && data != null) {
        BluetoothDevice deviceToPair =
data.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE);
        if (deviceToPair != null) {
            deviceToPair.createBond();
            // Continue to interact with the paired device.
        }
    } else {
        super.onActivityResult(requestCode, resultCode, data);
    }
}

पूरा उदाहरण देखें:

Android 13 (एपीआई लेवल 33) और उसके बाद के वर्शन वाले डिवाइसों पर:

Kotlin

private const val SELECT_DEVICE_REQUEST_CODE = 0

class MainActivity : AppCompatActivity() {

    private val deviceManager: CompanionDeviceManager by lazy {
        getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager
    }
    val mBluetoothAdapter: BluetoothAdapter by lazy {
        val java = BluetoothManager::class.java
        getSystemService(java)!!.adapter }
    val executor: Executor =  Executor { it.run() }

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

        // To skip filters based on names and supported feature flags (UUIDs),
        // omit calls to setNamePattern() and addServiceUuid()
        // respectively, as shown in the following  Bluetooth example.
        val deviceFilter: BluetoothDeviceFilter = BluetoothDeviceFilter.Builder()
            .setNamePattern(Pattern.compile("My device"))
            .addServiceUuid(ParcelUuid(UUID(0x123abcL, -1L)), null)
            .build()

        // The argument provided in setSingleDevice() determines whether a single
        // device name or a list of them appears.
        val pairingRequest: AssociationRequest = AssociationRequest.Builder()
            .addDeviceFilter(deviceFilter)
            .setSingleDevice(true)
            .build()

        // When the app tries to pair with a Bluetooth device, show the
        // corresponding dialog box to the user.
        deviceManager.associate(pairingRequest,
            executor,
            object : CompanionDeviceManager.Callback() {
                // Called when a device is found. Launch the IntentSender so the user
                // can select the device they want to pair with.
                override fun onAssociationPending(intentSender: IntentSender) {
                intentSender?.let {
                    startIntentSenderForResult(it, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
              }
            }

             override fun onAssociationCreated(associationInfo: AssociationInfo) {
                 // AssociationInfo object is created and get association id and the
                 // macAddress.
                 var associationId: int = associationInfo.id
                 var macAddress: MacAddress = associationInfo.deviceMacAddress
             }
             override fun onFailure(errorMessage: CharSequence?) {
                // Handle the failure.
            }
    )

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            SELECT_DEVICE_REQUEST_CODE -> when(resultCode) {
                Activity.RESULT_OK -> {
                    // The user chose to pair the app with a Bluetooth device.
                    val deviceToPair: BluetoothDevice? =
                        data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)
                    deviceToPair?.let { device ->
                        device.createBond()
                        // Maintain continuous interaction with a paired device.
                    }
                }
            }
            else -> super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

Java

class MainActivityJava extends AppCompatActivity {

    private static final int SELECT_DEVICE_REQUEST_CODE = 0;
    Executor executor = new Executor() {
        @Override
        public void execute(Runnable runnable) {
            runnable.run();
        }
    };

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

        CompanionDeviceManager deviceManager =
            (CompanionDeviceManager) getSystemService(
                Context.COMPANION_DEVICE_SERVICE
            );

        // To skip filtering based on name and supported feature flags,
        // do not include calls to setNamePattern() and addServiceUuid(),
        // respectively. This example uses Bluetooth.
        BluetoothDeviceFilter deviceFilter =
            new BluetoothDeviceFilter.Builder()
                .setNamePattern(Pattern.compile("My device"))
                .addServiceUuid(
                    new ParcelUuid(new UUID(0x123abcL, -1L)), null
                )
                .build();

        // The argument provided in setSingleDevice() determines whether a single
        // device name or a list of device names is presented to the user as
        // pairing options.
        AssociationRequest pairingRequest = new AssociationRequest.Builder()
            .addDeviceFilter(deviceFilter)
            .setSingleDevice(true)
            .build();

        // When the app tries to pair with the Bluetooth device, show the
        // appropriate pairing request dialog to the user.
        deviceManager.associate(pairingRequest, new CompanionDeviceManager.Callback() {
            executor,
           // Called when a device is found. Launch the IntentSender so the user can
           // select the device they want to pair with.
           @Override
           public void onDeviceFound(IntentSender chooserLauncher) {
               try {
                   startIntentSenderForResult(
                       chooserLauncher, SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0
                   );
               } catch (IntentSender.SendIntentException e) {
                   Log.e("MainActivity", "Failed to send intent");
               }
           }

          @Override
          public void onAssociationCreated(AssociationInfo associationInfo) {
                 // AssociationInfo object is created and get association id and the
                 // macAddress.
                 int associationId = associationInfo.getId();
                 MacAddress macAddress = associationInfo.getDeviceMacAddress();
          }

          @Override
          public void onFailure(CharSequence errorMessage) {
             // Handle the failure.
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == SELECT_DEVICE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                BluetoothDevice deviceToPair = data.getParcelableExtra(
                    CompanionDeviceManager.EXTRA_DEVICE
                );

                if (deviceToPair != null) {
                    deviceToPair.createBond();
                    // ... Continue interacting with the paired device.
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}

Android 12L (एपीआई लेवल 32) या इससे पहले के वर्शन वाले डिवाइसों पर (अब सेवा में नहीं है):

Kotlin

private const val SELECT_DEVICE_REQUEST_CODE = 0

class MainActivity : AppCompatActivity() {

    private val deviceManager: CompanionDeviceManager by lazy {
        getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager
    }

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

        // To skip filters based on names and supported feature flags (UUIDs),
        // omit calls to setNamePattern() and addServiceUuid()
        // respectively, as shown in the following  Bluetooth example.
        val deviceFilter: BluetoothDeviceFilter = BluetoothDeviceFilter.Builder()
            .setNamePattern(Pattern.compile("My device"))
            .addServiceUuid(ParcelUuid(UUID(0x123abcL, -1L)), null)
            .build()

        // The argument provided in setSingleDevice() determines whether a single
        // device name or a list of them appears.
        val pairingRequest: AssociationRequest = AssociationRequest.Builder()
            .addDeviceFilter(deviceFilter)
            .setSingleDevice(true)
            .build()

        // When the app tries to pair with a Bluetooth device, show the
        // corresponding dialog box to the user.
        deviceManager.associate(pairingRequest,
            object : CompanionDeviceManager.Callback() {

                override fun onDeviceFound(chooserLauncher: IntentSender) {
                    startIntentSenderForResult(chooserLauncher,
                        SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0)
                }

                override fun onFailure(error: CharSequence?) {
                    // Handle the failure.
                }
            }, null)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            SELECT_DEVICE_REQUEST_CODE -> when(resultCode) {
                Activity.RESULT_OK -> {
                    // The user chose to pair the app with a Bluetooth device.
                    val deviceToPair: BluetoothDevice? =
                        data?.getParcelableExtra(CompanionDeviceManager.EXTRA_DEVICE)
                    deviceToPair?.let { device ->
                        device.createBond()
                        // Maintain continuous interaction with a paired device.
                    }
                }
            }
            else -> super.onActivityResult(requestCode, resultCode, data)
        }
    }
}

Java

class MainActivityJava extends AppCompatActivity {

    private static final int SELECT_DEVICE_REQUEST_CODE = 0;

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

        CompanionDeviceManager deviceManager =
            (CompanionDeviceManager) getSystemService(
                Context.COMPANION_DEVICE_SERVICE
            );

        // To skip filtering based on name and supported feature flags,
        // don't include calls to setNamePattern() and addServiceUuid(),
        // respectively. This example uses Bluetooth.
        BluetoothDeviceFilter deviceFilter =
            new BluetoothDeviceFilter.Builder()
                .setNamePattern(Pattern.compile("My device"))
                .addServiceUuid(
                    new ParcelUuid(new UUID(0x123abcL, -1L)), null
                )
                .build();

        // The argument provided in setSingleDevice() determines whether a single
        // device name or a list of device names is presented to the user as
        // pairing options.
        AssociationRequest pairingRequest = new AssociationRequest.Builder()
            .addDeviceFilter(deviceFilter)
            .setSingleDevice(true)
            .build();

        // When the app tries to pair with the Bluetooth device, show the
        // appropriate pairing request dialog to the user.
        deviceManager.associate(pairingRequest,
            new CompanionDeviceManager.Callback() {
                @Override
                public void onDeviceFound(IntentSender chooserLauncher) {
                    try {
                        startIntentSenderForResult(chooserLauncher,
                            SELECT_DEVICE_REQUEST_CODE, null, 0, 0, 0);
                    } catch (IntentSender.SendIntentException e) {
                        // failed to send the intent
                    }
                }

                @Override
                public void onFailure(CharSequence error) {
                    // handle failure to find the companion device
                }
            }, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == SELECT_DEVICE_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK && data != null) {
                BluetoothDevice deviceToPair = data.getParcelableExtra(
                    CompanionDeviceManager.EXTRA_DEVICE
                );

                if (deviceToPair != null) {
                    deviceToPair.createBond();
                    // ... Continue interacting with the paired device.
                }
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}

साथी डिवाइस की प्रोफ़ाइलें

Android 12 (एपीआई लेवल 31) और उसके बाद वाले वर्शन पर, साथी ऐप्लिकेशन जो इस तरह के डिवाइसों को मैनेज करते हैं स्मार्टवॉच सेटअप करने की प्रोसेस को आसान बनाने के लिए, साथी डिवाइस की प्रोफ़ाइल का इस्तेमाल कर सकती है जोड़ते समय आवश्यक अनुमतियां देना. ज़्यादा जानकारी के लिए, यह देखें कंपैनियन डिवाइस की प्रोफ़ाइलें.

साथी ऐप्लिकेशन चालू रखें

Android 12 (एपीआई लेवल 31) और उसके बाद के वर्शन पर, मदद पाने के लिए अन्य एपीआई का इस्तेमाल किया जा सकता है जब तक आपका साथी डिवाइस रेंज में हो, तब तक आपका साथी ऐप्लिकेशन चलता रहता है. इन एपीआई से, आपको ये काम करने की सुविधा मिलती है:

  • जब कोई साथी डिवाइस रेंज में हो, तो अपने ऐप्लिकेशन की स्क्रीन चालू करें.

    जानकारी के लिए, यह देखें CompanionDeviceManager.startObservingDevicePresence().

  • यह गारंटी देता है कि ऐप्लिकेशन की प्रोसेस तब तक चलती रहेगी, जब तक आपका साथी डिवाइस रेंज में ही रहता है.

    जानकारी के लिए, यह देखें CompanionDeviceService.onDeviceAppeared().