How do I implement a BroadcastReceiver in a Service Class in Android?

寵の児 提交于 2019-12-03 09:20:31

问题


I need to implement BroadcastReceiver in a Service class I have created:

public class MyService extends Service

in this class I have to implement a Simulation of Download by using Thread - Sleep when the user presses the button in the MyActivity Class which implements sendBroadcas(). I cannot extends the Service class to BroadcastReceiver as it is already extendes to Service. Can anyone help me to figure it out how to implement this mechanism?

thanks


回答1:


Have the BroadcastReceiver as a top-level class or as an inner class in your service. And get a reference of the receiver in your service. Like this:

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);
    }
}


来源:https://stackoverflow.com/questions/18861279/how-do-i-implement-a-broadcastreceiver-in-a-service-class-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!