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

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

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

शुरू करें

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

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

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

उदाहरण के लिए, 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 API का इस्तेमाल करके, उपयोगकर्ता के हर दिन चले गए कदमों को पढ़ने का तरीका बताया गया है. किसी पूरे प्रोजेक्ट के संदर्भ में इसी तरह के लागू करने के तरीके को देखने के लिए, GitHub पर बेसिक हिस्ट्री एपीआईKotlin की ऐप्लिकेशन की मुख्य गतिविधि देखें.

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 services के एपीआई पर निर्भर, अपने ऐप्लिकेशन में किसी सुविधा को चालू करने से पहले, यह देख लें कि डिवाइस पर एपीआई उपलब्ध है या नहीं. ऐसा करने के लिए, 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."));
}