Case: A service sends a request to a remote server, dynamically updates the main program UI interface based on the results returned by the server, and the main program can shut down or restart services in real time.
Register Broadcastreceiver
Register a Broadcastreceiver in the main program activity to receive the broadcast of the Service release.
- @Override
- protected void OnStart () {//override OnStart method
- Datareceiver = new Datareceiver ();
- Intentfilter filter = new Intentfilter (); Create a Intentfilter object
- Filter.addaction ("Com.justel.serviceBC");
- Registerreceiver (datareceiver, filter); //Register broadcast Receiver
- Super.onstart ();
- }
Stop Service Command
The main program activity can publish broadcasts, which are used to pass data or control information, such as stop service commands, to the back-desk service.
- Btnstop.setonclicklistener (new Onclicklistener () {//Add click event Listener for button
- @Override
- public void onclick (View v) {//override onclick method
- Intent myintent = new Intent (); Create a Intent object
- Myintent.setaction ("Com.justel.service");
- Myintent.putextra ("cmd", cmd_stop_service);
- Sendbroadcast (myintent); //Send broadcast
- }
- });
Receive broadcasts
Background Service registration Broadcastreceiver to accept broadcasts sent by the main program
- @Override
- public int Onstartcommand (Intent Intent, int flags, int startid) {//override Onstartcommand method /c1>
- Intentfilter filter = new Intentfilter (); Create a Intentfilter object
- Filter.addaction ("Com.justel.service");
- Registerreceiver (cmdreceiver, filter); //Register broadcast Receiver
- Dojob (); //Call method to start the thread and do it yourself
- return Super.onstartcommand (intent, flags, Startid);
- }
Live Send
The background service connects to the server in the Dojob () method and sends broadcasts to the main program in real time.
- /**
- * Start a sub-purebred and connect to the server, the receiving server returns data. Code slightly ...
- */
- Object data; //data returned by the server
- Intent Intent = new Intent (); Create a Intent object
- Intent.setaction ("Com.justel.service");
- Intent.putextra ("data", data);
- Sendbroadcast (Intent); //Send broadcast
Implementation of the service dynamic update UI interface in Android