6

I would like to pass callback to IntentService. Here are my current codes:

My callback interface

import android.os.Message;

public interface SampleCallback {

    public void doSomethingFromCurrentThread();

    public void doSomethingFromUIThread(final Message msg);
}

My IntentService

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SampleCallbackIntentService extends IntentService {
    private final String LOG_LOGCAT_TAG = "SampleCallbackIntentService";
    private final SampleCallback _callback;
    private Handler _handler;

    public SampleCallbackIntentService(String name, SampleCallback callback) {
        super(name);
        _callback = callback;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        // initialize variables for pause & resume thread
        _mPauseLock = new Object();
        _mPaused = false;
        _mFinished = false;

        // initialize handler to switch to UI/Main thread
         _handler = new Handler()
            {
                @Override
                public void handleMessage(final Message msg)
                {
                    _callback.doSomethingFromUIThread(msg);
                }
            };
    }

    private final int CALLBACK_MESSAGE = 1;
    @Override
    protected void onHandleIntent(Intent arg0) {
        Log.i(LOG_LOGCAT_TAG, "loop started");
        while (!_mFinished) {
            // do stuff here
            _callback.doSomethingFromCurrentThread();

            // process and create the result to pass
            String someResult = "some result here";
            _handler.sendMessage(_handler.obtainMessage(CALLBACK_MESSAGE, someResult));

            synchronized (_mPauseLock) {
                while (_mPaused) {
                    try {
                        Log.i(LOG_LOGCAT_TAG, "loop paused");
                        _mPauseLock.wait();
                        Log.i(LOG_LOGCAT_TAG, "loop resumed");
                    } catch (InterruptedException e) {
                        Log.e(LOG_LOGCAT_TAG, "error occured on pause", e);
                    }
                }
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                Log.e(LOG_LOGCAT_TAG, "error occured on sleep", e);
            }
        }
        Log.i(LOG_LOGCAT_TAG, "loop ended");
    }

    private Object _mPauseLock;
    private boolean _mPaused;
    private boolean _mFinished;

    /**
     * Call this on pause.
     */
    public void pause() {
        Log.i(LOG_LOGCAT_TAG, "pause() called");
        synchronized (_mPauseLock) {
            _mPaused = true;
        }
    }

    /**
     * Call this on resume.
     */
    public void resume() {
        Log.i(LOG_LOGCAT_TAG, "resume() called");
        synchronized (_mPauseLock) {
            _mPaused = false;
            _mPauseLock.notifyAll();
        }
    }
}

Any guidance on how to pass my callback is appreciated.

eros
  • 4,946
  • 18
  • 53
  • 78
  • I've seen this link => http://stackoverflow.com/questions/3921269/how-to-implement-callbacks-using-intentservice-on-android but don't have clear answer. For that, I provide my source code to start with. – eros Aug 26 '11 at 04:22
  • My next questions are on how to call pause() and resume(). I will post another question for that. Regards – eros Aug 26 '11 at 04:23

2 Answers2

9

You might be looking for a ResultReceiver. It implements Parcelable so you can pass it to an intent service.

Sorry for giving you an answer 4 years later.

midnightstar
  • 572
  • 5
  • 13
  • Be careful when you do this however because you might accidentally leak views. Take a look at this [video](https://www.youtube.com/watch?v=BkbHeFHn8JY&index=6&list=PLWz5rJ2EKKc9CBxr3BVjPTPoDPLdPIFCE) for more information Try to use a weak reference to the activity to help prevent the leak. – midnightstar Sep 05 '15 at 18:55
3

Here's a good answer about notifying an activity from a service: Notify activity from service. As for me, Activity.createPendingResult() is a great way to call parent activity.

That's not actually a callback but AFAIK there's no good way to implement such a callback without bound service.

Community
  • 1
  • 1
Michael
  • 53,859
  • 22
  • 133
  • 139
  • How can I implement it with bound service? Is there a practical example on the net? If yes, could you please share the url.. Regards... – eros Aug 29 '11 at 00:14
  • Oh, I forgot to add a link I was talking about. Fixed it. – Michael Aug 29 '11 at 04:01
  • And I'd recommend not to use bound services. If you tell me what you want to do I'll try to give you a link or an example of code. – Michael Aug 29 '11 at 04:11
  • My apology for delayed response. I am evaluating an Location API called Skyhook which is have callback interface. Callback methods will be utilized upon calling getLocation(auth, _callback). If succeed, _callback.handleSuccess(location) will be called. If failed, _callback.handleError(location). Then, want to call the getLocation inside the Service repeatedly. I have tried before Java in Web apps but upon reading the Android documentation, I realized that it is totally different approach although it uses Java as a programming language. Regards. – eros Sep 02 '11 at 01:32
  • 2
    Here's a good tutorial for you: http://mindtherobot.com/blog/37/android-architecture-tutorial-developing-an-app-with-a-background-service-using-ipc/ – Michael Sep 02 '11 at 06:05