Androi Service+broadcast+timer+ui "Judging by binding service, custom callback interface

Source: Internet
Author: User

Recent projects to periodically from the server to obtain some information, through the study to summarize the next "I judge the network status as an example to illustrate"


We define a service that sets a timer in the service to check the current application's network connection status through the TimerTask policy. The key is that the service needs to customize a callback interface for sending the network state back to our activity, then bind the current service through BIND, and get callback information after the binding succeeds


service class

Package com.example.androidtimerdemo;import java.util.timer;import java.util.timertask;import;import android.content.BroadcastReceiver;import android.content.Context; import android.content.intent;import android.content.intentfilter;import;import;import; import android.os.binder;import android.os.ibinder;import android.util.log;import  android.widget.toast;public class netservice extends service{@Overridepublic  ibinder  onbind (intent intent) {// todo auto-generated method stubreturn netbind;} Context context context;//Network connection Status boolean isconntect = true;    //timer  timer = new timer (); @Overridepublic  void oncreate () {//  registered Radio      Check network status Intentfilter filter = neW intentfilter (); filter.addaction ( ConnectivityManager.CONNECTIVITY_ACTION ); Registerreceiver (  receiver, filter ); LOG.I (  "tag",  "service**" +thread.currentthread (). GetId ()  ); Super.oncreate ();} Network Check broadcast recipient Private broadcastreceiver receiver = new broadcastreceiver () {@ Overridepublic void onreceive (context context, intent intent) {String action  = intent.getaction ();//  Start the scheduled task if  (Action.equals ( connectivitymanager.connectivity_ action )) {//start now, execute once every 5 seconds tasklog.i (  "tag",  "receiver**" +thread.currentthread (). GetId ()  ); Timer.schedule ( new nettask ( context ), 0, 5*1000 )}}};/ /specific TimerTask implementation class Class nettask extends timertask{public nettask (CONTEXT CONTEXT1) { Context = context1;} @Overridepublic  void run () {try{thread.sleep ( 20*1000 );} catch  (Interruptedexception e){// todo auto-generated catch blocke.printstacktrace ();} if  (Isconnectnet ()) {isconntect = true;} Else{isconntect = false;} LOG.I (  "tag",  "run**" +thread.currentthread (). GetId ()  );if  (ongetconnectstate !=  NULL) {ongetconnectstate.getstate ( isConntect ); //  notifies network state changes}}}//  network state changes, Notifies the state of the current network through an instance of this interface, which injects an instance object into the activity public interface getconnectstate{public void getstate (boolean isconnected); }private getconnectstate ongetconnectstate;public void  Setongetconnectstate (getconnectstate ongetconnectstate) {this.ongetconnectstate =  Ongetconnectstate;} /** *  determine if the network is connected  *  @return  */private boolean isconnectnet () { connectivitymanager connectivitymanager =  (Connectivitymanager)  context.getSystemService (  Context.CONNECTIVITY_SERVICE ); Networkinfo mobile = connectivitymAnager.getnetworkinfo ( ConnectivityManager.TYPE_MOBILE ); Networkinfo wifi = connectivitymanager.getnetworkinfo ( ConnectivityManager.TYPE_WIFI  );if  (Mobile.getstate (). Equals ( State.DISCONNECTED )  && wifi.getstate (). Equals ( State.DISCONNECTED )) {return false;} Return true;}  //defines a bind class Private netbind netbind = new netbind ();class netbind  Extends binder{public netservice getnetservice () {return netservice.this;}} Destroy broadcast, stop timed polling @overridepublic void ondestroy () {// todo auto-generated method  Stubsuper.ondestroy (); Timer.cancel (); Unregisterreceiver ( receiver );}}


Package com.example.androidtimerdemo;import java.util.timer;import java.util.timertask;import  com.example.androidtimerdemo.MybindService.MyBind;import  com.example.androidtimerdemo.netservice.getconnectstate;import  com.example.androidtimerdemo.netservice.netbind;import android.os.bundle;import android.os.handler; import android.os.ibinder;import android.os.message;import;import  Android.content.componentname;import android.content.context;import android.content.intent;import  android.content.serviceconnection;import android.util.log;import;import  android.view.view;import android.view.view.onclicklistener;import android.widget.button;import  android.widget.TextView;import android.widget.Toast;public class MainActivity  extends activity implements onclicklistener{textview textview; textview textview2; Button button1, button2; activity activity; @Overrideprotected  void oncreate (bundle savedinstancestate) { Super.oncreate ( savedInstanceState ); Setcontentview ( R.layout.activity_main ); activity  = this;initview ();} Private void initview () {textview =  (TextView)  findviewbyid (  );textview2 =  (TextView)  findviewbyid ( );button1 =  (Button)  findviewbyid ( );button2 =  (Button)  findviewbyid (  ); Button1.setonclicklistener ( this ); Button2.setonclicklistener ( this );} boolean is; @Overridepublic  void onclick (view v) {switch  (V.getid ()) {case  binding service LOG.I (  "tag",  "click**"  + thread.currentthread (). GetId ()  ); I Ntent intent = new intent ( activity, NetService.class ); BOOLEAN&NBsp;istrue = bindservice ( intent, conn, Context.BIND_AUTO_CREATE ); is =  istrue;break;case ();d efault:break;}} Private void unbind () {if  (conn != null) {unbindservice ( conn );}} private boolean conncetstate = true;private serviceconnection conn =  New serviceconnection () {@Overridepublic  void onservicedisconnected (componentname name) {//  todo auto-generated method stub} @Overridepublic  void onserviceconnected ( Componentname name, ibinder service) {netbind bind =  (NetBind)  service; Netservice netservice = bind.getnetservice ();             //here Callback Netservice.setongetconnectstate ( new getconnectstate () {@Overridepublic  void getstate (boolean isconnected) {// todo auto-generated method stubif  (conncetstate != isconnected) {conncetstate = isconnected;} Message msg = handler.obtainmessage ();if  (conncetstate) {msg.what = 1;} Else{msg.what = 2;} Handler.sendmessage ( msg );}}  );}}; Handler handler = new handler () {public void handlemessage (Message msg) { switch  (msg.what) {case 1:toast.maketext ( activity,  connect, 2000 ). Show (); Break;case 2:toast.maketext ( activity,  "not", 2000 ). Show ();d Efault:break;}};};

Androi Service+broadcast+timer+ui "Judging by binding service, custom callback interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.