gpt4 book ai didi

java - BroadcastReceiver中调用类函数的onReceive函数

转载 作者:行者123 更新时间:2023-11-30 04:10:02 28 4
gpt4 key购买 nike


我有一个带有 BroadcastReceiver 的服务。
我如何从 onReceive 函数调用服务类中的函数 BroadcastReceiver?
如果我不能,我能做什么?
这是一些代码:

public class MyService extends Service {
private BroadcastReceiver broadcastReceiver;

@Override
public IBinder onBind(Intent arg0) {
return null;
}

@Override
public void onCreate() {
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
... // How to call myFunction() here?
}
};
... // intentFilter, registerReceiver, etc...
}

private void myFunction() {
... // do something
}
}

最佳答案

你可以这样调用它:

    broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
myFunction();
}
};

或者,如果 myFunctionBroadcastReceiver 方法同名,您可以像这样显式调用外部类方法:

    broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
MyService.this.myFunction();
}
};

关于java - BroadcastReceiver中调用类函数的onReceive函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11005187/

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