Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 a Thread - Sleep when the user presses the button in the MyActivity class which implements sendBroadcast(). I cannot extend the Service class to BroadcastReceiver as it is already extends to Service. Can anyone help me to figure it out how to implement this mechanism?

like image 921
Dilshad Abduwali Avatar asked Sep 17 '13 23:09

Dilshad Abduwali


People also ask

How is broadcast receiver implemented?

An application listens for specific broadcast intents by registering a broadcast receiver in AndroidManifest. xml file. Consider we are going to register MyReceiver for system generated event ACTION_BOOT_COMPLETED which is fired by the system once the Android system has completed the boot process.

Where do I register and unregister broadcast receiver?

You should register and unregister your broadcast in onResume() and onPause() methods. if you register in onStart() and unregister it in onStop().

What is the role of the onReceive () method in the BroadcastReceiver?

Retrieve the current result extra data, as set by the previous receiver. This can be called by an application in onReceive(Context, Intent) to allow it to keep the broadcast active after returning from that function.


1 Answers

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);
    }
}
like image 109
Steve Benett Avatar answered Sep 23 '22 02:09

Steve Benett