我想將回調傳遞給IntentService。這裏是我當前的代碼:Android:IntentService:如何:將回調傳遞給Activity中的IntentService?
我的回調接口
import android.os.Message;
public interface SampleCallback {
public void doSomethingFromCurrentThread();
public void doSomethingFromUIThread(final Message msg);
}
我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();
}
}
}
如何通過我的回調任何指導表示讚賞。
我看過這個鏈接=> http://stackoverflow.com/questions/3921269/how-to-implement-callbacks-using-intentservice-on-android但沒有明確的答案。爲此,我提供了我的源代碼。 – eros
我的下一個問題是如何調用pause()和resume()。我會爲此發佈另一個問題。問候 – eros