Google API ऐक्सेस करें

जब किसी SDK टूल के साथ काम करने वाले किसी एपीआई को कॉल करना हो Google Play सेवाएं, जैसे कि Google साइन-इन या ML किट का इस्तेमाल करने के लिए, आपको ये काम करने होंगे एपीआई क्लाइंट ऑब्जेक्ट का इंस्टेंस बनाएं. ये ऑब्जेक्ट अपने-आप मैनेज होते हैं Google Play services से कनेक्ट करता है. कनेक्शन उपलब्ध होने पर, हर एपीआई क्लाइंट ऑब्जेक्ट, अनुरोधों को क्रम में एक्ज़ीक्यूट करता है. ऐसा न करने पर, क्लाइंट ऑब्जेक्ट सूची में जुड़ जाएगा अनुरोध. जब तक दस्तावेज़ में कोई दूसरी जानकारी न दी जाए, क्लाइंट ऑब्जेक्ट सस्ते होते हैं बनाने के लिए; हर बार शुरू करने के लिए, नए एपीआई क्लाइंट बनाए जा सकते हैं एपीआई के तरीके.

इस गाइड में, इस्तेमाल किए जा रहे किसी भी SDK टूल पर एपीआई कॉल करने का तरीका बताया गया है इसमें उन सेवाओं को ऐक्सेस करने का तरीका भी शामिल है जो आपके ऐप्लिकेशन में उपलब्ध नहीं हैं अनुमति ज़रूरी है और जिन्हें की ज़रूरत होती है अनुमति देना.

अपनी प्रोफ़ाइल बनाना शुरू करें

शुरू करने के लिए, अपने ऐप्लिकेशन प्रोजेक्ट में ज़रूरी टूल और डिपेंडेंसी जोड़ें, जैसे कि Google Play खाता सेट अप करने के बारे में गाइड में बताया गया है सेवाएं.

अनुमति की ज़रूरत न होने पर ऐक्सेस करें

किसी ऐसी सेवा को ऐक्सेस करने के लिए जिसके लिए एपीआई की अनुमति की ज़रूरत नहीं होती, का उपयोग करने के लिए Context या मौजूदा Activity. किसी भी एपीआई कॉल के शुरू होने से पहले, उपयोगकर्ताओं को Google Play अपग्रेड करने के लिए कहा जाएगा सेवाओं का इस्तेमाल करने के लिए किया जा सकता है.

उदाहरण के लिए, अलग-अलग तरह की जगह की जानकारी का इस्तेमाल करके, डिवाइस की आखिरी जगह की जानकारी का पता लगाना Android की सेवा देने वाली कंपनी, इस कोड स्निपेट में दिखाए गए लॉजिक को जोड़ें:

Kotlin

// Code required for requesting location permissions omitted for brevity.
val client = LocationServices.getFusedLocationProviderClient(this)

// Get the last known location. In some rare situations, this can be null.
client.lastLocation.addOnSuccessListener { location : Location? ->
    location?.let {
        // Logic to handle location object.
    }
}

Java

// Code required for requesting location permissions omitted for brevity.
FusedLocationProviderClient client =
        LocationServices.getFusedLocationProviderClient(this);

// Get the last known location. In some rare situations, this can be null.
client.getLastLocation()
        .addOnSuccessListener(this, location -> {
            if (location != null) {
                // Logic to handle location object.
            }
        });

अनुमति की ज़रूरत होने पर ऐक्सेस करें

किसी ऐसी सेवा को ऐक्सेस करने के लिए जिसमें उपयोगकर्ता की अनुमति की ज़रूरत हो, इन चरणों को पूरा करें: कदम:

  1. उपयोगकर्ता को साइन इन करने दें.
  2. सेवा के लिए ज़रूरी स्कोप को ऐक्सेस करने की अनुमति मांगें.
  3. सेवा के क्लाइंट ऑब्जेक्ट का इंस्टेंस पाएं, जो उसे उपयोगकर्ता के पास भेज रहा है GoogleSignInAccount एक के अतिरिक्त Context या Activity ऑब्जेक्ट है.

नीचे दिए गए उदाहरण में Google Fit एपीआई. पूरे प्रोजेक्ट के लिए इसी तरह का तरीका देखने के लिए, की मुख्य गतिविधि BasicHistoryApiKotlin GitHub पर मौजूद ऐप्लिकेशन खोलें.

Kotlin

class FitFragment : Fragment() {
    private val fitnessOptions: FitnessOptions by lazy {
        FitnessOptions.builder()
            .addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
            .addDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .build()
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        fitSignIn()
    }

    /*
     * Checks whether the user is signed in. If so, executes the specified
     * function. If the user is not signed in, initiates the sign-in flow,
     * specifying the function to execute after the user signs in.
     */
    private fun fitSignIn() {
        if (oAuthPermissionsApproved()) {
            readDailySteps()
        } else {
            GoogleSignIn.requestPermissions(
                this,
                SIGN_IN_REQUEST_CODE,
                getGoogleAccount(),
                fitnessOptions
            )
        }
    }

    private fun oAuthPermissionsApproved() =
        GoogleSignIn.hasPermissions(getGoogleAccount(), fitnessOptions)

    /*
     * Gets a Google account for use in creating the fitness client. This is
     * achieved by either using the last signed-in account, or if necessary,
     * prompting the user to sign in. It's better to use the
     * getAccountForExtension() method instead of the getLastSignedInAccount()
     * method because the latter can return null if there has been no sign in
     * before.
     */
    private fun getGoogleAccount(): GoogleSignInAccount =
        GoogleSignIn.getAccountForExtension(requireContext(), fitnessOptions)

    /*
     * Handles the callback from the OAuth sign in flow, executing the function
     * after sign-in is complete.
     */
    override fun onActivityResult(
            requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (resultCode) {
            RESULT_OK -> {
                readDailySteps()
            }
            else -> {
                // Handle error.
            }
        }
    }

    /*
     * Reads the current daily step total.
     */
    private fun readDailySteps() {
        Fitness.getHistoryClient(requireContext(), getGoogleAccount())
            .readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
            .addOnSuccessListener { dataSet ->
                val total = when {
                    dataSet.isEmpty -> 0
                    else -> dataSet.dataPoints.first()
                            .getValue(Field.FIELD_STEPS).asInt()
                }

                Log.i(TAG, "Total steps: $total")
            }
            .addOnFailureListener { e ->
                Log.w(TAG, "There was a problem getting the step count.", e)
            }
    }

    companion object {
        const val SIGN_IN_REQUEST_CODE = 1001
    }
}

Java

public class FitFragment extends Fragment {
    private final FitnessOptions fitnessOptions = FitnessOptions.builder()
            .addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE)
            .addDataType(DataType.TYPE_STEP_COUNT_DELTA)
            .build();

    @Override
    public void onViewCreated(
            @NotNull View view, @Nullable Bundle savedInstanceState) {
        fitSignIn();
    }

    /*
     * Checks whether the user is signed in. If so, executes the specified
     * function. If the user is not signed in, initiates the sign-in flow,
     * specifying the function to execute after the user signs in.
     */
    private void fitSignIn() {
        if (oAuthPermissionsApproved()) {
            readDailySteps();
        } else {
            GoogleSignIn.requestPermissions(this, SIGN_IN_REQUEST_CODE,
                    getGoogleAccount(), fitnessOptions);
        }
    }

    private boolean oAuthPermissionsApproved() {
        return GoogleSignIn.hasPermissions(getGoogleAccount(), fitnessOptions);
    }

    /*
     * Gets a Google account for use in creating the fitness client. This is
     * achieved by either using the last signed-in account, or if necessary,
     * prompting the user to sign in. It's better to use the
     * getAccountForExtension() method instead of the getLastSignedInAccount()
     * method because the latter can return null if there has been no sign in
     * before.
     */
    private GoogleSignInAccount getGoogleAccount() {
        return GoogleSignIn.getAccountForExtension(
                requireContext(), fitnessOptions);
    }

    /*
     * Handles the callback from the OAuth sign in flow, executing the function
     * after sign-in is complete.
     */
    @Override
    public void onActivityResult(
            int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            readDailySteps();
        } else {
            // Handle error.
        }
    }

    /*
     * Reads the current daily step total.
     */
    private void readDailySteps() {
        AtomicInteger total = new AtomicInteger();
        Fitness.getHistoryClient(requireContext(), getGoogleAccount())
                .readDailyTotal(DataType.TYPE_STEP_COUNT_DELTA)
                .addOnSuccessListener(dataSet -> {
                    if (!dataSet.isEmpty())
                        total.set(Integer.parseInt(dataSet.getDataPoints()
                                .get(0).getValue(FIELD_STEPS).toString()));
                        Log.i(TAG, "Total steps: $total");
                })
                .addOnFailureListener(e -> {
                    Log.w(TAG, "There was a problem getting the step count.", e);
                });
    }

    private static final int SIGN_IN_REQUEST_CODE = 1001;
}

देखें कि एपीआई उपलब्ध है या नहीं

इससे पहले कि आप अपने ऐप्लिकेशन में किसी ऐसी सुविधा को चालू करें जो Google Play सेवाओं पर निर्भर करती है एपीआई का इस्तेमाल करते समय, डिवाइस पर एपीआई की उपलब्धता की जांच करें. ऐसा करने के लिए, checkApiAvailability() को कॉल करें.

नीचे दिया गया कोड स्निपेट, एक ही जगह से दूसरी जगह से कनेक्ट करने वाली सेवा.

Kotlin

fun getLastLocationIfApiAvailable(context: Context?): Task<Location>? {
    val client = getFusedLocationProviderClient(context)
    return GoogleApiAvailability.getInstance()
        .checkApiAvailability(client)
        .onSuccessTask { _ -> client.lastLocation }
        .addOnFailureListener { _ -> Log.d(TAG, "Location unavailable.")}
}

Java

public Task<Location> getLastLocationIfApiAvailable(Context context) {
    FusedLocationProviderClient client =
            getFusedLocationProviderClient(context);
    return GoogleApiAvailability.getInstance()
            .checkApiAvailability(client)
            .onSuccessTask(unused -> client.getLastLocation())
            .addOnFailureListener(e -> Log.d(TAG, "Location unavailable."));
}