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"
Principle:
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
Code:
service class
Package com.example.androidtimerdemo;import java.util.timer;import java.util.timertask;import android.app.Service;import android.content.BroadcastReceiver;import android.content.Context; import android.content.intent;import android.content.intentfilter;import android.net.connectivitymanager;import android.net.networkinfo;import android.net.networkinfo.state; 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 );}}
Activity:
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 android.app.activity;import Android.content.componentname;import android.content.context;import android.content.intent;import android.content.serviceconnection;import android.util.log;import android.view.menu;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 ( R.id.textView1 );textview2 = (TextView) findviewbyid ( R.id.textView2 );button1 = (Button) findviewbyid ( R.id.button1 );button2 = (Button) findviewbyid ( r.id.button2 ); Button1.setonclicklistener ( this ); Button2.setonclicklistener ( this );} boolean is; @Overridepublic void onclick (view v) {switch (V.getid ()) {case r.id.button1:// 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 r.id.button2:unbind ();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