gpt4 book ai didi

android - 从服务到 Activity 的 ResultReceiver

转载 作者:行者123 更新时间:2023-11-30 01:16:57 30 4
gpt4 key购买 nike

我有一个在后台运行的服务,它从一个 Activity 开始,并且在没有 Activity 的情况下完成它的工作。使用 ResultReceiver,我可以与 Activity 进行通信,但只要 Activity 处于 Activity 状态即可。一旦销毁并重新启动,就没有与 Activity 的通信。我做错了什么?

        // Activity
public void onReceiveResult(int resultCode, Bundle resultData) {
String test = resultData.getString("Event");
}
public MyResultReceiver mReceiver;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

mReceiver = new MyResultReceiver(new Handler());
mReceiver.setReceiver(this);


Intent i=new Intent(this, AppService.class);

i.putExtra(AppService.TIME, spinner_time.getSelectedItemPosition());

startService(i);


// Service

public class AppService extends Service {

public static final String TIME="TIME";

int time_loud;

Notification note;
Intent i;

private boolean flag_silencemode = false;


@Override
public int onStartCommand(Intent intent, int flags, int startId) {


time_loud = intent.getIntExtra(TIME, 0);
resultReceiver = intent.getParcelableExtra(RESULT_RECEIVER);
resultData = new Bundle();

resultData.putString("Event", "ysfgsdfgsdfg");
resultReceiver.send(55, resultData);

play(time_loud);

return(START_NOT_STICKY);
}


@SuppressLint("ParcelCreator")
public class MyResultReceiver extends ResultReceiver {

private Receiver mReceiver;

public MyResultReceiver(Handler handler) {
super(handler);
}

public void setReceiver(Receiver receiver) {
mReceiver = receiver;
}

public interface Receiver {
void onReceiveResult(int resultCode, Bundle resultData);
}

@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
if (mReceiver != null) {
mReceiver.onReceiveResult(resultCode, resultData);
}
}
}

最佳答案

为简单起见,使用本地广播管理器,并在您的 Activity onResume 和 onPause 生命周期中注册和注销它

关于android - 从服务到 Activity 的 ResultReceiver,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37710193/

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