java.lang.ClassCastException: android.os.BinderProxy cannot be cast to LocalBinder

This question is a few years old and the accepted answer didn't work for me. Perhaps something has changed in the Android environment since the question was asked and answered.

But I stumbled on a simple solution that worked. I saw another question on SO that was trying to start 2 services and they had a similar error (Getting java.lang.ClassCastException: android.os.BinderProxy every time i declare and run two services). One of the answers (@Coeffect) mentioned that the 2 services don't necessarily run in the same process.

I got to thinking that it is possible (probable?) that in my case the activity and the service were run in different processes. So I added the android:process element to both my activity and my server, and that fixed it.

Here's an example AndroidManifest.xml. Note that both the <activity> and <service> tags include android:process=":location":

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="net.byteslinger.locationservice">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:process=":location"
        android:allowBackup="true"
        android:icon="@mipmap/icon"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/icon"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity"
            android:process=":location"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service
            android:process=":location"
            android:name=".LocationService"
            android:enabled="true" />
    </application>

</manifest>

You've got it flipped:

public void onServiceConnected(ComponentName name, IBinder service) {
    LocalBinder binder = (LocalBinder) service;
    service = (IBinder) binder.getService();
    ...
}

should be:

public void onServiceConnected(ComponentName name, IBinder service) {
    LocalBinder binder = (LocalBinder) service;
    MainActivity.this.service = (ConnectionService) binder.getService();
    ...
}