我需要在我创建的Service类中实现BroadcastReceiver:
public class MyService extends Service
在这个类中,当用户按下实现sendBroadcas()的MyActivity类中的按钮时,我必须通过使用Thread – Sleep来实现下载模拟.我不能将Service类扩展为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); } }