Auf Google APIs zugreifen

Wenn Sie eine der APIs in einem SDK aufrufen möchten, das auf Google Play-Dienste wie Google Log-in oder ML Kit müssen Sie zuerst eine Instanz eines API-Client-Objekts zu erstellen. Diese Objekte verwalten die Verbindung zu den Google Play-Diensten. Wenn eine Verbindung verfügbar ist, Clientobjekt führt Anfragen der Reihe nach aus. Andernfalls werden die Clientobjekte der Anfragen. Sofern in der Dokumentation nicht anders angegeben, sind Client-Objekte günstig. konstruktiv; können Sie jedes Mal, wenn Sie einen Aufruf von API-Methoden.

In diesem Leitfaden erfahren Sie, wie Sie API-Aufrufe an alle unterstützten SDKs senden. die Google Play-Dienste betreffen, einschließlich des Zugriffs auf Dienste, die nicht und solche, die eine Autorisierung erfordern, Autorisierung.

Erste Schritte

Fügen Sie Ihrem App-Projekt zunächst die erforderlichen Tools und Abhängigkeiten hinzu, in der Anleitung zur Einrichtung von Google Play Dienste.

Zugriff, wenn keine Autorisierung erforderlich ist

Rufen Sie für den Zugriff auf einen Dienst, der keine API-Autorisierung erfordert, eine Instanz von das Clientobjekt des Dienstes, indem es entweder den aktuellen Context oder die aktuelle Activity Bevor API-Aufrufe ausgeführt werden, werden Nutzer aufgefordert, Google Play zu aktualisieren oder Services von Google.

Um den letzten bekannten Standort des Geräts mithilfe der Funktion Anbieter für Android fügen Sie die Logik aus dem folgenden Code-Snippet hinzu:

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.
            }
        });

Zugriff, wenn eine Autorisierung erforderlich ist

Für den Zugriff auf einen Dienst, für den eine Nutzerautorisierung erforderlich ist, führen Sie die folgenden Schritte aus: Schritte:

  1. Melden Sie den Nutzer an.
  2. Fordern Sie die Berechtigung zum Zugriff auf die Bereiche an, die der Dienst benötigt.
  3. Ruft eine Instanz des Clientobjekts des Dienstes ab und übergibt ihr die GoogleSignInAccount -Objekt zusätzlich zu einem Context oder Activity -Objekt enthält.

Im folgenden Beispiel wird das Lesen der täglichen Schritte eines Nutzers mithilfe der Google Fit API Um eine ähnliche Implementierung im Kontext eines vollständigen Projekts zu sehen, die Hauptaktivität der BasicHistoryApiKotlin App auf 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;
}

API-Verfügbarkeit prüfen

Bevor Sie eine Funktion in Ihrer App aktivieren, die von einem Google Play-Dienst abhängig ist API, einschließlich einer Prüfung der Verfügbarkeit der API auf dem Gerät. Gehen Sie dazu wie folgt vor: Rufen Sie checkApiAvailability() auf.

Das folgende Code-Snippet zeigt, wie Sie die Verfügbarkeit des Anbieter für kombinierte Standortbestimmung.

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."));
}