سؤال

The client code for binding to a service, which is normally in the activity class; I'm trying to move it to the service class, so that the activity class would be as clean and small as possible.

i.e. basically trying to merge the code in the second box here into the first box = as much of it into the service class as possible

Single Line in Activity for Binding to Service

public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Bind to service with this line only:
    AService.bindService(this);
}
}

Static bindService and ServiceConnection Moved to Service

public class AService extends Service {

public String test = "I want to see this";
public static AService aService;
private static boolean isBound;
private static Context context;

// ... IBinder, onBind etc also here on service side

public static void bindService(Context context) {
    try {
        Log.i(TAG, "bindService Start");
        if (!isBound && context != null) {
            Log.i(TAG, "Binding");
            context.bindService(new Intent(context, AService.class),
                    serviceConnection, Context.BIND_AUTO_CREATE);
            isBound = true;
            Log.i(TAG, "Bound");
        }
    } catch (Exception e) {
        Log.e(TAG, "bindService", e);
    }
}

private static ServiceConnection serviceConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder service) {
        try {
            Log.i(TAG, "onServiceConnected Start");
            aService = ((AService.LocalBinder) service).getService();
            if (aService != null)
                Log.i(TAG, aService.test);
            Log.i(TAG, "onServiceConnected Finish");
        } catch (Exception e) {
            Log.e(TAG, "onServiceConnected", e);
        }
    }

    public void onServiceDisconnected(ComponentName className) {
        try {
            Log.i(TAG, "onServiceDisconnected");
            aService = null;
        } catch (Exception e) {
            Log.e(TAG, "onServiceDisconnected", e);
        }
    }
};


public static void unbind() {
    try {
        Log.i(TAG, "unbind start");
        if (isBound && context != null) {
            Log.i(TAG, "Unbinding");
            context.unbindService(serviceConnection);
            isBound = false;
            context = null;
            Log.i(TAG, "Unbound");
        }
    } catch (Exception e) {
        Log.e(TAG, "unbind", e);
    }
}

}

But onServiceConnected is Never Called?

The log shows everything up to:

...
Bound
  • But NOT onServiceConnected Start or beyond
  • and no exceptions.
  • Note that when the same code was in the Activity, it works (when called with MyActivity.this)

What am I doing wrong?

لا يوجد حل صحيح

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top