Search code examples
androidservicebind

Android Can't call methods in a local service, and Googles sample code will not compile


I’m trying to make a client call functions on a locakl service. I founbd the following documentation on google. Which said a local service could use the Bind interface, url at google android with documention and sample code I used http://developer.android.com/guide/topics/fundamentals/bound-services.html#Creating But I cannot get the sample code for there service, to compile!. Where the code has

public class LocalBinder extends Binder {

        // error here //    LocalService getService() {
                // Return this instance of LocalService so clients can call public methods
           // error hear //     return LocalService.this;
            }

I get a error saying LocalService cannot be resolved to a type. I was thinking I’m missing a import. I tried to google android localservice I got another linbk to samople code on google to do the same thing http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/app/LocalService.html and it had the same error!!!!

The complete code

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.os.Binder;
import android.widget.Toast;


    public class BackgroundService extends Service {
        // Binder given to clients
        private final IBinder mBinder = new LocalBinder();
        // Random number generator
        private final Random mGenerator = new Random();

        /**
         * Class used for the client Binder.  Because we know this service always
         * runs in the same process as its clients, we don't need to deal with IPC.
         */
        public class LocalBinder extends Binder {

            LocalService getService() {
                // Return this instance of LocalService so clients can call public methods
                return LocalService.this;
            }

        }

        @Override
        public IBinder onBind(Intent intent) {
            return mBinder;
        }

        /** method for clients */
        public int getRandomNumber() {
          return mGenerator.nextInt(100);
        }
    }

Solution

  • You called your service "BackgroundService". Return that in the binder. (Change LocalSerivce to BackgroundSerivice in two places)