You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Awareness API已废弃,咨询同时获取位置与活动的替代API方案

Alternatives to Deprecated Google Awareness API: Combining Activity Recognition & Fused Location Provider

Hey there! Great question—since the Awareness API is indeed deprecated, you’re right to look for alternatives, and Activity Recognition API combined with Fused Location Provider API is exactly the fully supported, reliable replacement you need to get both user activity and location data.

Why This Combo Works

  • Fused Location Provider: Google’s recommended tool for location data. It’s optimized for battery life and accuracy, supporting both foreground and background location updates.
  • Activity Recognition API: Uses device sensors and machine learning to detect user activities (walking, driving, running, stationary, etc.) with high precision.

Code Example: Implementing the Combo

First, add the required dependency to your app-level build.gradle (module level):

dependencies {
    implementation 'com.google.android.gms:play-services-location:21.0.1'
}

1. Initialize Clients in Your Activity/Fragment

Replace your old GoogleApiClient setup with these modern, supported clients:

import com.google.android.gms.location.ActivityRecognitionClient
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    private lateinit var fusedLocationClient: FusedLocationProviderClient
    private lateinit var activityRecognitionClient: ActivityRecognitionClient

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

        // Initialize location and activity clients
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
        activityRecognitionClient = LocationServices.getActivityRecognitionClient(this)
    }
}

2. Request Location Updates

Get accurate, optimized location data with the Fused Location Provider:

import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationResult
import android.Manifest
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import android.os.Looper

private fun startLocationUpdates() {
    val locationRequest = LocationRequest.create().apply {
        interval = 10000 // Update every 10 seconds
        fastestInterval = 5000 // Fastest update interval (5 seconds)
        priority = LocationRequest.PRIORITY_HIGH_ACCURACY
    }

    val locationCallback = object : LocationCallback() {
        override fun onLocationResult(locationResult: LocationResult) {
            locationResult.lastLocation?.let { location ->
                // Use the location data (latitude, longitude, etc.)
                val latitude = location.latitude
                val longitude = location.longitude
                // Add your logic here
            }
        }
    }

    // Check for location permission first
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
        == PackageManager.PERMISSION_GRANTED
    ) {
        fusedLocationClient.requestLocationUpdates(
            locationRequest,
            locationCallback,
            Looper.getMainLooper()
        )
    }
}

3. Request Activity Recognition Updates

Detect user activities with the Activity Recognition API:

import com.google.android.gms.location.ActivityRecognitionResult
import com.google.android.gms.location.DetectedActivity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.app.PendingIntent

private lateinit var activityReceiver: BroadcastReceiver

private fun startActivityRecognition() {
    // Broadcast receiver to handle activity updates
    activityReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (ActivityRecognitionResult.hasResult(intent)) {
                val result = ActivityRecognitionResult.extractResult(intent)
                val detectedActivities = result.probableActivities
                
                detectedActivities.forEach { activity ->
                    when (activity.type) {
                        DetectedActivity.WALKING -> { /* User is walking */ }
                        DetectedActivity.IN_VEHICLE -> { /* User is in a vehicle */ }
                        DetectedActivity.STILL -> { /* User is stationary */ }
                        // Handle other activity types as needed
                    }
                }
            }
        }
    }

    // Register the receiver
    registerReceiver(activityReceiver, IntentFilter("com.your.package.ACTIVITY_UPDATES"))

    // Create pending intent for activity updates
    val intent = Intent("com.your.package.ACTIVITY_UPDATES")
    val pendingIntent = PendingIntent.getBroadcast(
        this,
        0,
        intent,
        PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
    )

    // Check for activity recognition permission first
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
        == PackageManager.PERMISSION_GRANTED
    ) {
        activityRecognitionClient.requestActivityUpdates(10000, pendingIntent) // 10-second interval
    }
}

Key Reminders

  • Add these permissions to your AndroidManifest.xml:
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
    
  • Always request runtime permissions before accessing location or activity data.
  • Unregister the broadcast receiver and stop updates when they’re no longer needed (e.g., in onDestroy()) to save battery.

内容的提问来源于stack exchange,提问作者Lalit Jadav

火山引擎 最新活动