我需要在我创建的服务类中实现 BroadcastReceiver:
public class MyService extends Service
在这个类中,当用户按下MyActivity
实现类中的按钮时,我必须使用 Thread-Sleep 来实现下载的模拟sendBroadcast()
。我无法将 Service 类扩展到,BroadcastReceiver
因为它已经扩展到Service
. 谁能帮我弄清楚如何实现这个机制?
我需要在我创建的服务类中实现 BroadcastReceiver:
public class MyService extends Service
在这个类中,当用户按下MyActivity
实现类中的按钮时,我必须使用 Thread-Sleep 来实现下载的模拟sendBroadcast()
。我无法将 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);
}
}