androi之Service+Broadcast+Timer+ui【通过绑定服务、自定义回调接口判断网络连接】

来源:互联网 发布:linux 饥荒服务器 编辑:程序博客网 时间:2024/05/13 06:38

分类: android 550人阅读 评论(0) 收藏 举报
AndroidAndroid移动开发Timer 定时netbroadcast

      最近项目要定时从服务器获取某些信息,通过研究来总结一下下【我以定时判断网络状态为例来阐述】

     原理:

    我们定义一个Service,在该Service中设置一个定时器Timer,通过TimerTask的策略来检查当前应用的网络连接状态,关键是在该Service需要自定义一个回调接口用于向我们的Activity来回调发送网络状态,然后通过Bind来绑定当前的Service,在绑定成功之后得到回调信息

  代码:

Service类

  

[java] view plaincopy
  1. package com.example.androidtimerdemo;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import android.app.Service;  
  7. import android.content.BroadcastReceiver;  
  8. import android.content.Context;  
  9. import android.content.Intent;  
  10. import android.content.IntentFilter;  
  11. import android.net.ConnectivityManager;  
  12. import android.net.NetworkInfo;  
  13. import android.net.NetworkInfo.State;  
  14. import android.os.Binder;  
  15. import android.os.IBinder;  
  16. import android.util.Log;  
  17. import android.widget.Toast;  
  18.   
  19. public class NetService extends Service  
  20. {  
  21.   
  22.     @Override  
  23.     public IBinder onBind(Intent intent)  
  24.     {  
  25.         // TODO Auto-generated method stub  
  26.         return netBind;  
  27.     }  
  28.   
  29.     //上下文  
  30.     Context context;  
  31.       
  32.     //网络连接状态  
  33.     boolean isConntect = true;  
  34.       
  35.     //定时器  
  36.     Timer timer = new Timer();  
  37.   
  38.     @Override  
  39.     public void onCreate()  
  40.     {  
  41.         // 注册广播   检查网络状态  
  42.         IntentFilter filter = new IntentFilter();  
  43.         filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION );  
  44.         registerReceiver( receiver, filter );  
  45.         Log.i( "tag""service**"+Thread.currentThread().getId() );  
  46.         super.onCreate();  
  47.     }  
  48.   
  49.     //网络检查广播接受者  
  50.     private BroadcastReceiver receiver = new BroadcastReceiver()  
  51.     {  
  52.   
  53.         @Override  
  54.         public void onReceive(Context context, Intent intent)  
  55.         {  
  56.             String action = intent.getAction();  
  57.             // 启动定时任务  
  58.             if (action.equals( ConnectivityManager.CONNECTIVITY_ACTION ))  
  59.             {  
  60.                 //立即启动,每隔5秒执行一次Task  
  61.                 Log.i( "tag""receiver**"+Thread.currentThread().getId() );  
  62.                 timer.schedule( new NetTask( context ), 05*1000 );  
  63.             }  
  64.         }  
  65.     };  
  66.   
  67.     //具体的TimerTask实现类  
  68.     class NetTask extends TimerTask  
  69.     {  
  70.   
  71.         public NetTask(Context context1)  
  72.         {  
  73.             context = context1;  
  74.         }  
  75.   
  76.   
  77.         @Override  
  78.         public void run()  
  79.         {  
  80.               
  81.             try  
  82.             {  
  83.                 Thread.sleep( 20*1000 );  
  84.             }  
  85.             catch (InterruptedException e)  
  86.             {  
  87.                 // TODO Auto-generated catch block  
  88.                 e.printStackTrace();  
  89.             }  
  90.               
  91.             if (isConnectNet())  
  92.             {  
  93.                 isConntect = true;  
  94.             }  
  95.             else  
  96.             {  
  97.                 isConntect = false;  
  98.             }  
  99.             Log.i( "tag""run**"+Thread.currentThread().getId() );  
  100.             if (onGetConnectState != null)  
  101.             {  
  102.                 onGetConnectState.GetState( isConntect ); // 通知网络状态改变  
  103.             }  
  104.         }  
  105.   
  106.     }  
  107.   
  108.     // 网络状态改变之后,通过此接口的实例通知当前网络的状态,此接口在Activity中注入实例对象  
  109.     public interface GetConnectState  
  110.     {  
  111.         public void GetState(boolean isConnected);   
  112.     }  
  113.   
  114.     private GetConnectState onGetConnectState;  
  115.   
  116.   
  117.     public void setOnGetConnectState(GetConnectState onGetConnectState)  
  118.     {  
  119.         this.onGetConnectState = onGetConnectState;  
  120.     }  
  121.   
  122.   
  123.     /** 
  124.      * 判断是否连通网络 
  125.      * @return 
  126.      */  
  127.     private boolean isConnectNet()  
  128.     {  
  129.         ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService( Context.CONNECTIVITY_SERVICE );  
  130.         NetworkInfo Mobile = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_MOBILE );  
  131.   
  132.         NetworkInfo Wifi = connectivityManager.getNetworkInfo( ConnectivityManager.TYPE_WIFI );  
  133.         if (Mobile.getState().equals( State.DISCONNECTED ) && Wifi.getState().equals( State.DISCONNECTED ))  
  134.         {  
  135.             return false;  
  136.         }  
  137.         return true;  
  138.     }  
  139.   
  140.       
  141.      //定义一个Bind类  
  142.     private NetBind netBind = new NetBind();  
  143.     class NetBind extends Binder  
  144.     {  
  145.         public NetService getNetService()  
  146.         {  
  147.             return NetService.this;  
  148.         }  
  149.     }  
  150.   
  151.   
  152.     //销毁广播、停止定时轮询  
  153.     @Override  
  154.     public void onDestroy()  
  155.     {  
  156.         // TODO Auto-generated method stub  
  157.         super.onDestroy();  
  158.         timer.cancel();  
  159.         unregisterReceiver( receiver );  
  160.     }  
  161.   
  162. }  

Activity:

 

[java] view plaincopy
  1. package com.example.androidtimerdemo;  
  2.   
  3. import java.util.Timer;  
  4. import java.util.TimerTask;  
  5.   
  6. import com.example.androidtimerdemo.MybindService.MyBind;  
  7. import com.example.androidtimerdemo.NetService.GetConnectState;  
  8. import com.example.androidtimerdemo.NetService.NetBind;  
  9.   
  10. import android.os.Bundle;  
  11. import android.os.Handler;  
  12. import android.os.IBinder;  
  13. import android.os.Message;  
  14. import android.app.Activity;  
  15. import android.content.ComponentName;  
  16. import android.content.Context;  
  17. import android.content.Intent;  
  18. import android.content.ServiceConnection;  
  19. import android.util.Log;  
  20. import android.view.Menu;  
  21. import android.view.View;  
  22. import android.view.View.OnClickListener;  
  23. import android.widget.Button;  
  24. import android.widget.TextView;  
  25. import android.widget.Toast;  
  26.   
  27. public class MainActivity extends Activity implements OnClickListener  
  28. {  
  29.   
  30.     TextView textView;  
  31.   
  32.     TextView textView2;  
  33.   
  34.     Button button1, button2;  
  35.   
  36.     Activity activity;  
  37.   
  38.   
  39.     @Override  
  40.     protected void onCreate(Bundle savedInstanceState)  
  41.     {  
  42.         super.onCreate( savedInstanceState );  
  43.         setContentView( R.layout.activity_main );  
  44.         activity = this;  
  45.         initView();  
  46.     }  
  47.   
  48.   
  49.     private void initView()  
  50.     {  
  51.         textView = (TextView) findViewById( R.id.textView1 );  
  52.         textView2 = (TextView) findViewById( R.id.textView2 );  
  53.         button1 = (Button) findViewById( R.id.button1 );  
  54.         button2 = (Button) findViewById( R.id.button2 );  
  55.         button1.setOnClickListener( this );  
  56.         button2.setOnClickListener( this );  
  57.   
  58.     }  
  59.   
  60.     boolean is;  
  61.   
  62.   
  63.     @Override  
  64.     public void onClick(View v)  
  65.     {  
  66.         switch (v.getId())  
  67.         {  
  68.             case R.id.button1:  
  69.                 // 绑定服务  
  70.                 Log.i( "tag""click**" + Thread.currentThread().getId() );  
  71.                 Intent intent = new Intent( activity, NetService.class );  
  72.                 boolean isTrue = bindService( intent, conn, Context.BIND_AUTO_CREATE );  
  73.                 is = isTrue;  
  74.                 break;  
  75.             case R.id.button2:  
  76.                 unBind();  
  77.             default:  
  78.                 break;  
  79.         }  
  80.     }  
  81.   
  82.   
  83.     private void unBind()  
  84.     {  
  85.         if (conn != null)  
  86.         {  
  87.             unbindService( conn );  
  88.         }  
  89.     }  
  90.   
  91.     private boolean conncetState = true;  
  92.   
  93.     private ServiceConnection conn = new ServiceConnection()  
  94.     {  
  95.   
  96.         @Override  
  97.         public void onServiceDisconnected(ComponentName name)  
  98.         {  
  99.             // TODO Auto-generated method stub  
  100.   
  101.         }  
  102.   
  103.   
  104.         @Override  
  105.         public void onServiceConnected(ComponentName name, IBinder service)  
  106.         {  
  107.   
  108.             NetBind bind = (NetBind) service;  
  109.             NetService netService = bind.getNetService();  
  110.             //此处回调  
  111.             netService.setOnGetConnectState( new GetConnectState()  
  112.             {  
  113.   
  114.                 @Override  
  115.                 public void GetState(boolean isConnected)  
  116.                 {  
  117.                     // TODO Auto-generated method stub  
  118.                     if (conncetState != isConnected)  
  119.                     {  
  120.                         conncetState = isConnected;  
  121.                     }  
  122.                     Message msg = handler.obtainMessage();  
  123.                     if (conncetState)  
  124.                     {  
  125.                         msg.what = 1;  
  126.                     }  
  127.                     else  
  128.                     {  
  129.                         msg.what = 2;  
  130.                     }  
  131.                     handler.sendMessage( msg );  
  132.                 }  
  133.             } );  
  134.   
  135.         }  
  136.     };  
  137.   
  138.     Handler handler = new Handler()  
  139.     {  
  140.         public void handleMessage(Message msg)  
  141.         {  
  142.             switch (msg.what)  
  143.             {  
  144.                 case 1:  
  145.                     Toast.makeText( activity, "connect"2000 ).show();  
  146.                     break;  
  147.                 case 2:  
  148.                     Toast.makeText( activity, "not"2000 ).show();  
  149.                 default:  
  150.                     break;  
  151.             }  
  152.         };  
  153.     };  
  154.   
  155. }  

PS:记得加网络权限哦
0 0
原创粉丝点击