gpt4 book ai didi

android - 如何在 Android 的服务类中实现 BroadcastReceiver?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:35:44 25 4
gpt4 key购买 nike

我需要在我创建的服务类中实现 BroadcastReceiver:

public class MyService extends Service

在这个类中,我必须通过使用线程实现下载模拟 - 当用户按下实现 sendBroadcast()MyActivity 类中的按钮时休眠。我无法将服务类扩展到 BroadcastReceiver,因为它已经扩展到 Service。谁能帮我弄清楚如何实现这个机制?

最佳答案

在您的服务中将 BroadcastReceiver 作为顶级类或内部类。并在您的服务中获得接收者的引用。像这样:

public class MyService extends Service {
BroadcastReceiver mReceiver;

// use this as an inner class like here or as a top-level class
public class MyReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
// do something
}

// constructor
public MyReceiver(){

}
}

@Override
public void onCreate() {
// get an instance of the receiver in your service
IntentFilter filter = new IntentFilter();
filter.addAction("action");
filter.addAction("anotherAction");
mReceiver = new MyReceiver();
registerReceiver(mReceiver, filter);
}
}

关于android - 如何在 Android 的服务类中实现 BroadcastReceiver?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18861279/

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