gpt4 book ai didi

android - 从 AsyncTask 到 Activity 的消息

转载 作者:太空宇宙 更新时间:2023-11-03 13:36:50 24 4
gpt4 key购买 nike

我正在尝试从服务中嵌入的异步任务向我的主要 Activity 发送消息。基本上,异步任务必须在输入时阻塞,它不能在主 Activity 线程中运行(阻塞已从下面的示例代码中删除)。但是当数据进来时,我需要将它发送到主要 Activity 。我发现下面发送的消息永远不会成功。如果答案是在异步任务中移动绑定(bind),您该怎么做?如果可能的话,指向示例代码会有很大帮助。

public class InputService2 extends Service {
int bufferSize = 1024;
Process process;
DataInputStream os;
TextView inputView;
byte[] buffer = new byte[bufferSize];
private MyAsyncTask inputTask = null;
public void onCreate(){
inputTask = new MyAsyncTask();
inputTask.execute((Void[])null);

}
private class MyAsyncTask extends AsyncTask<Void,Void,Void> {

int mValue = 0;
static final int MSG_SET_VALUE = 3;
protected void onProgressUpdate(Void progress){

}

protected void onPostExecute(Void result) {

}

protected Void doInBackground(Void... params) {

int i = 0;


try {
mValue = 0x23;
Message message = Message.obtain(null,MSG_SET_VALUE,mValue,0);
mMessenger.send(message);
}
catch (Exception e) {

}


}
}
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
}
}
final Messenger mMessenger = new Messenger(new IncomingHandler());
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}

}

下面是 Activity 内部:

class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Context context = getApplicationContext();
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, msg.arg1, duration);
toast.show();
}
}

boolean mBound;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the object we can use to
// interact with the service. We are communicating with the
// service using a Messenger, so here we get a client-side
// representation of that from the raw IBinder object.
mService = new Messenger(service);
mBound = true;
}

public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
mService = null;
mBound = false;
}
};

protected void onStart() {
super.onStart();
// Bind to the service
bindService(new Intent(this, InputService2.class), mConnection,
Context.BIND_AUTO_CREATE);
}

最佳答案

看起来您的示例基于 http://developer.android.com/reference/android/app/Service.html#RemoteMessengerServiceSample 处的 javadoc 引用,但是您遗漏了很多实际使它起作用的实现细节。您必须返回并实现该示例中引用的全部功能才能使用该特定模式:请仔细注意 IncomingHandler 类中的 REGISTER_CLIENT 和 UN_REGISTER_CLIENT 实现部分,因为这些是实际确保 Message 可以从为 Activity 服务。

关于android - 从 AsyncTask 到 Activity 的消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6052586/

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