We have previously introduced you to the Android UI design and background threading interaction, according to the Android API, the service is generally run in the background, there is no interface. So how to implement the service dynamic update UI interface.
Case: Send a request to a remote server through a service, dynamically update the main UI interface based on the results returned by the server, and the main program can shut down or restart the service in real time. Register Broadcastreceiver
Registers a broadcastreceiver in the main program activity to receive broadcasts from service announcements.
@Override protected void OnStart () {//rewrite OnStart method datareceiver = new Datareceiver (); Intentfilter filter = new Intentfilter ();//Create Intentfilter Object Filter.addaction ("Com.justel.serviceBC"); Registerreceiver (Datareceiver, filter),//Registered broadcast Receiver Super.onstart (); }
Stop Service Command
The main program activity can publish broadcasts to pass data or control information to the back desk service, such as stopping the service command.
Btnstop.setonclicklistener (New Onclicklistener () {//button to add Click event Listener @Override public void OnClick (View v) {//rewrite o Nclick method Intent myintent = new Intent ();//Create Intent Object Myintent.setaction ("Com.justel.service"); Myintent.putextra ("cmd", cmd_stop_service); Sendbroadcast (myintent);//Send Broadcast}});
Receive broadcast
Background Service registration Broadcastreceiver is used to accept broadcasts sent by the main program
@Override public int Onstartcommand (Intent Intent, int flags, int startid) {//overriding Onstartcommand method Intentfilter Filte R = new Intentfilter ();//Create Intentfilter Object Filter.addaction ("Com.justel.service"); Registerreceiver (cmdreceiver, filter);//Register Broadcast Receiver dojob ();//Call method start thread, finish return yourself Super.onstartcomm and (intent, flags, Startid); }
send in real time
The background service connects the server in the Dojob () method and sends broadcasts to the main program in real time.
/** * Start a child purebred and connect to the server, the receiving server returns data. Code slightly ... */Object data;//server returned data Intent Intent = new Intent ();//Create Intent Object Intent.setaction ("Com.justel.service"); Intent.putextra ("Data", data); Sendbroadcast (intent);/Send Broadcast
So far, we have implemented the UI interface that the main program updates the application in real time by receiving broadcasts.