gpt4 book ai didi

java - 当类从线程扩展时,如何使用 resultreceiver 发送数据

转载 作者:行者123 更新时间:2023-12-01 14:11:12 28 4
gpt4 key购买 nike

我有一个服务类,我可以通过它向我的 Activity 发送一些数据

public class baseApi extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//get the receiver object
resultReceiver = intent.getParcelableExtra("receiver");
}


private BroadcastReceiver datachanged_receiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
//HERE I send some data like this
Bundle bundle = new Bundle();
bundle.putString("data", "My data goes here");
resultReceiver.send(100, bundle);
}};
}

在同一个类中,我有一个扩展“线程”的类,并且该类还打算使用 resultReceiver 向 UI 发送一些数据,它不会给出任何异常,但 UI 端也没有收到任何数据,而通过广播接收器发送数据的 resultReceiver 效果很好。

public class baseApi extends Service {

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//get the receiver object
resultReceiver = intent.getParcelableExtra("receiver");
}


private BroadcastReceiver datachanged_receiver = new BroadcastReceiver() {

@Override
public void onReceive(Context context, Intent intent) {
//HERE I send some data like this
Bundle bundle = new Bundle();
bundle.putString("data", "My data goes here");
resultReceiver.send(100, bundle);
}};

class actionThread extends Thread{
@Override
public void run() {
super.run();
try{
//send this data to the service
Bundle bundle = new Bundle();
bundle.putString("data","More data goes here" );
resultReceiver.send(200, bundle);
}
catch(Exception ex)
{

}
}

}
}

最佳答案

在android中,您可以使用Handler与UI线程进行通信。只需使用 Hanlder.PostHandlerThread 即可。

关于java - 当类从线程扩展时,如何使用 resultreceiver 发送数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18510455/

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