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

AndroidX迁移Google Transport Tracker Demo遇崩溃及API弃用问题

Hey there! Let's tackle your two issues one by one—they're both common when migrating older Google Play Services code to AndroidX, so we'll get you sorted out quickly.


1. Fixing the Deprecated GoogleApiClient.Builder

GoogleApiClient has been deprecated for several years, and Google now recommends using FusedLocationProviderClient for location services. It's simpler, more maintainable, and aligns with modern Android best practices. Here's how to update your code:

Step 1: Replace the GoogleApiClient instance

Update your TrackerService class to use the new client:

// Remove the old GoogleApiClient declaration
// private GoogleApiClient mGoogleApiClient;

// Add this instead
private FusedLocationProviderClient mFusedLocationClient;

Step 2: Initialize the client in onCreate

@Override
public void onCreate() {
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) buildNotification();
    else startForeground(1, new Notification());
    setStatusMessage(R.string.connecting);
    
    // Initialize the FusedLocationProviderClient
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    
    // ... existing Firebase and auth code ...
}

Step 3: Rewrite startLocationTracking and remove connection callbacks

You won't need the old ConnectionCallbacks anymore—replace the entire startLocationTracking method and related code:

private void startLocationTracking() {
    startForegroundService();
    requestLocationUpdates();
}

private LocationRequest createLocationRequest() {
    LocationRequest request = LocationRequest.create();
    request.setInterval(mFirebaseRemoteConfig.getLong("LOCATION_REQUEST_INTERVAL"));
    request.setFastestInterval(mFirebaseRemoteConfig.getLong("LOCATION_REQUEST_INTERVAL_FASTEST"));
    request.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    return request;
}

private void requestLocationUpdates() {
    try {
        mFusedLocationClient.requestLocationUpdates(
            createLocationRequest(),
            this, // Your LocationListener implementation
            Looper.getMainLooper()
        );
        setStatusMessage(R.string.tracking);
        
        // Keep your wakelock code as-is
        PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        mWakelock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakelockTag");
        mWakelock.acquire();
    } catch (SecurityException e) {
        Log.e(TAG, "Missing location permission", e);
        Toast.makeText(this, R.string.location_permission_missing, Toast.LENGTH_SHORT).show();
        stopSelf();
    }
}

Step 4: Update onDestroy to clean up correctly

@Override
public void onDestroy() {
    setStatusMessage(R.string.not_tracking);
    mNotificationManager.cancel(NOTIFICATION_ID);
    
    // Use the new client to remove location updates
    if (mFusedLocationClient != null) {
        mFusedLocationClient.removeLocationUpdates(this);
    }
    
    if (mWakelock != null) { mWakelock.release(); }
    super.onDestroy();
}

2. Fixing the "Invalid Channel for Service Notification" Crash

Your crash happens because of two issues:

  • Mismatched notification channel IDs between channel creation and the notification builder
  • Improper channel initialization before using the notification

Here's the fixed buildNotification method:

// Add these constants at the top of your TrackerService class
private static final String NOTIFICATION_CHANNEL_ID = "com.google.transporttracker.background";
private static final String NOTIFICATION_CHANNEL_NAME = "Transport Tracker Background";

private void buildNotification() {
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

    // Create the channel for Android O+ first
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationChannel channel = new NotificationChannel(
            NOTIFICATION_CHANNEL_ID,
            NOTIFICATION_CHANNEL_NAME,
            NotificationManager.IMPORTANCE_LOW // Use LOW for foreground services to avoid intrusive alerts
        );
        channel.setDescription("Background service for tracking transport location");
        mNotificationManager.createNotificationChannel(channel);
    }

    PendingIntent resultPendingIntent = PendingIntent.getActivity(
        this,
        0,
        new Intent(this, TrackerActivity.class),
        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE // Add FLAG_IMMUTABLE for API 31+
    );

    mNotificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
            .setSmallIcon(R.drawable.bus_white)
            .setColor(getColor(R.color.colorPrimary))
            .setContentTitle(getString(R.string.app_name))
            .setOngoing(true)
            .setContentIntent(resultPendingIntent)
            .setPriority(NotificationCompat.PRIORITY_LOW);

    startForeground(FOREGROUND_SERVICE_ID, mNotificationBuilder.build());
}

Bonus: Fix notification ID consistency

In your setStatusMessage method, use the same ID you used for startForeground to avoid confusion:

private void setStatusMessage(int stringId) {
    mNotificationBuilder.setContentText(getString(stringId));
    mNotificationManager.notify(FOREGROUND_SERVICE_ID, mNotificationBuilder.build()); // Use FOREGROUND_SERVICE_ID here
    // ... existing broadcast code ...
}

Bonus: Clean Up Your Dependencies

You have duplicate and outdated dependencies in your build.gradle—this can cause conflicts. Here's the cleaned-up version:

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.gms:play-services-maps:17.0.0'
    testImplementation 'junit:junit:4.12'
    implementation 'androidx.appcompat:appcompat:1.0.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation "com.google.android.gms:play-services-gcm:17.0.0"
    implementation "com.google.android.gms:play-services-location:17.0.0" // Removed duplicate entry
    implementation "com.google.firebase:firebase-auth:19.3.2"
    implementation "com.google.firebase:firebase-config:19.2.0"
    implementation "com.google.firebase:firebase-database:19.3.1"
    implementation "com.google.android.gms:play-services-base:17.0.0"
    // Removed com.android.support:design (you're already using AndroidX Material)
}

Once you apply these changes, both the deprecated GoogleApiClient warning and the notification channel crash should be resolved. Don't forget to test that location permissions are granted (Android 6.0+ requires runtime permissions) and that the notification channel appears in your device's settings.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 20:47:40