In addition to ibinder, you can also use broadcast receiver for communication between activity and service.
Case: send a request to the remote server through the service and dynamically update the master node based on the results returned by the serverProgramUi. The main program can shut down or restart the service in real time.
Register a broadcastreceiver in the main program activity to receive the broadcast published by the Service.
@ Override
Protected void onstart () {// rewrite the onstart Method
Datareceiver = new datareceiver ();
Intentfilter filter = new intentfilter (); // create an intentfilter object
Filter. addaction ("Your. Action ");
Registerreceiver (datareceiver, filter); // register broadcast Receiver
Super. onstart ();
}
The main program activity can publish a broadcast to transmit data or control information to the background service, such as stopping the service command.
Btnstop. setonclicklistener (New onclicklistener () {// Add a click event listener for the button
@ Override
Public void onclick (view v) {// override the onclick Method
Intent myintent = new intent (); // create an intent object
Myintent. setaction ("Your. Action ");
Myintent. putextra ("cmd", cmd_stop_service );
Sendbroadcast (myintent); // send Broadcast
}
});
The backend service registers broadcastreceiver for receiving broadcasts sent by the main program.
@ Override
Public int onstartcommand (intent, int flags, int startid) {// override the onstartcommand Method
Intentfilter filter = new intentfilter (); // create an intentfilter object
Filter. addaction ("Your. Action ");
Registerreceiver (cmdreceiver, filter); // register broadcast Receiver
Dojob (); // call the method to start the thread and complete it by yourself
Return super. onstartcommand (intent, flags, startid );
}
The Background Service sends broadcast messages to the main program in real time.
Object Data; // data returned by the server
Intent intent = new intent (); // create an intent object
Intent. setaction ("com. justel. Service ");
Intent. putextra ("data", data );
Sendbroadcast (intent); // send Broadcast
This removes the dependency between the activity and service.