You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何构建Release模式的Android应用?GoogleFit: RESULT_CANCELED错误解决求助

Hey Caitlin, let's break down how to fix your two main issues: getting your Android (Java) app built correctly in Release mode, and resolving that frustrating Google Fit RESULT_CANCELED error that's closing your Activity. I’ve dealt with similar problems before, so let’s walk through this step by step.

1. Properly Building Your App in Release Mode

First, let’s make sure your Release build setup is solid—since you mentioned you already updated Gradle, let’s double-check the critical parts:

  • Verify Gradle Signing Configuration
    Release builds require a signed APK/AAB, so confirm your app/build.gradle has a valid signing config linked to the release build type:

    android {
        compileSdkVersion 34 // Use your target SDK version
        defaultConfig {
            applicationId "com.your.app.id"
            minSdkVersion 26
            targetSdkVersion 34
            // ... other configs
        }
    
        buildTypes {
            release {
                minifyEnabled true // Optional, but common for Release
                proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
                signingConfig signingConfigs.release // This is mandatory!
                debuggable false // Set to true temporarily if you need to debug Release build
            }
        }
    
        // Configure your release keystore
        signingConfigs {
            release {
                storeFile file("your-release-keystore.jks")
                storePassword "your-keystore-password"
                keyAlias "your-key-alias"
                keyPassword "your-key-password"
            }
        }
    }
    

    Sync Gradle after making changes.

  • Trigger the Release Build

    • In Android Studio: Go to Build > Generate Signed Bundle/APK, select APK or AAB, follow the prompts to use your release keystore.
    • Or use command line:
      Mac/Linux: ./gradlew assembleRelease
      Windows: gradlew.bat assembleRelease
      The built file will be in app/build/outputs/apk/release/ (or bundle/release for AAB).
2. Fixing Google Fit RESULT_CANCELED & Permission Issues

The "can’t enter permission screen + RESULT_CANCELED" problem usually ties to missing permissions, incorrect OAuth setup, or Release-specific config gaps. Let’s troubleshoot:

  • Double-Check Permissions in Manifest & Dynamic Requests
    Google Fit requires both manifest declarations AND dynamic permission requests (for Android 10+):

    1. Add these to AndroidManifest.xml:
      <uses-permission android:name="android.permission.INTERNET" />
      <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
      <!-- Add data-specific permissions you need, e.g., for steps: -->
      <uses-permission android:name="com.google.android.gms.permission.FITNESS_ACTIVITY_READ" />
      <uses-permission android:name="com.google.android.gms.permission.FITNESS_ACTIVITY_WRITE" />
      
    2. Request ACTIVITY_RECOGNITION dynamically before asking for Google Fit authorization:
      private static final int REQUEST_ACTIVITY_RECOGNITION = 1001;
      private static final int REQUEST_GOOGLE_FIT = 1002;
      
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          checkActivityRecognitionPermission();
      }
      
      private void checkActivityRecognitionPermission() {
          if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACTIVITY_RECOGNITION)
                  != PackageManager.PERMISSION_GRANTED) {
              ActivityCompat.requestPermissions(this,
                      new String[]{Manifest.permission.ACTIVITY_RECOGNITION},
                      REQUEST_ACTIVITY_RECOGNITION);
          } else {
              requestGoogleFitAuth();
          }
      }
      
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
          super.onRequestPermissionsResult(requestCode, permissions, grantResults);
          if (requestCode == REQUEST_ACTIVITY_RECOGNITION) {
              if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  requestGoogleFitAuth();
              } else {
                  Toast.makeText(this, "Activity recognition permission is required for Google Fit", Toast.LENGTH_SHORT).show();
              }
          }
      }
      
  • Validate Google Fit Authorization Flow
    Make sure your auth code is correctly set up to handle results:

    private void requestGoogleFitAuth() {
           FitnessOptions fitnessOptions = FitnessOptions.builder()
                   .addDataType(DataType.TYPE_STEP_COUNT_CUMULATIVE, FitnessOptions.ACCESS_READ)
                   // Add other data types you need access to
                   .build();
    
           GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this);
           if (account == null) {
               // Prompt user to sign in to Google first
               GoogleSignIn.requestSignIn(this, fitnessOptions);
           } else if (!GoogleSignIn.hasPermissions(account, fitnessOptions)) {
               GoogleSignIn.requestPermissions(
                       this,
                       REQUEST_GOOGLE_FIT,
                       account,
                       fitnessOptions);
           } else {
               // Already authorized—proceed with Fit API calls
               fetchFitData();
           }
       }
    
       @Override
       protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
           super.onActivityResult(requestCode, resultCode, data);
           if (requestCode == REQUEST_GOOGLE_FIT) {
               if (resultCode == RESULT_OK) {
                   fetchFitData();
               } else if (resultCode == RESULT_CANCELED) {
                   // This is your error—check these common fixes:
                   // 1. Is the user signed into a valid Google account on the device?
                   // 2. Is Google Fit app installed and updated?
                   // 3. Did you add your Release build's SHA-1 to Google Cloud Console?
                   Toast.makeText(this, "Google Fit authorization canceled", Toast.LENGTH_SHORT).show();
               }
           }
       }
    
  • Critical: Add Release SHA-1 to Google Cloud Console
    This is the #1 mistake developers make with Release mode Google Fit issues:

    1. Get your Release keystore’s SHA-1 fingerprint using this command:
      keytool -list -v -keystore your-release-keystore.jks -alias your-key-alias
      
    2. Go to your Google Cloud Project → APIs & Services → Credentials.
    3. Find your OAuth 2.0 Client ID (for Android) → Edit → Add the Release SHA-1 to the "Signing-certificate fingerprint" section → Save.
  • Fix ProGuard Obfuscation (If Enabled)
    If you have minifyEnabled true in Release build, add these rules to proguard-rules.pro to avoid breaking Google Fit API:

    -keep class com.google.android.gms.** { *; }
    -dontwarn com.google.android.gms.**
    
Final Tips

If you’re still stuck:

  • Temporarily set debuggable true in your Release build type, then connect your device and use Logcat to capture detailed error logs when the RESULT_CANCELED occurs—this will show exactly why the auth is failing.
  • Verify that your Google Cloud Project has the Fit API enabled (APIs & Services → Library → Search for "Fitness" → Enable).

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 19:07:39