gpt4 book ai didi

Android:IntentService:如何:将回调从 Activity 传递到 IntentService?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:03:39 25 4
gpt4 key购买 nike

我想将回调传递给 IntentService。这是我当前的代码:

我的回调接口(interface)

import android.os.Message;

public interface SampleCallback {

public void doSomethingFromCurrentThread();

public void doSomethingFromUIThread(final Message msg);
}

我的 Intent 服务

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();
}
}
}

感谢任何关于如何传递我的回调的指导。

最佳答案

您可能正在寻找 ResultReceiver .它实现了 Parcelable,因此您可以将其传递给 Intent 服务。

很抱歉在 4 年后给你一个答案。

关于Android:IntentService:如何:将回调从 Activity 传递到 IntentService?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7199981/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com