首页 > 代码库 > androi之Service+Broadcast+Timer+ui【通过绑定服务、自定义回调接口判断
androi之Service+Broadcast+Timer+ui【通过绑定服务、自定义回调接口判断
最近项目要定时从服务器获取某些信息,通过研究来总结一下下【我以定时判断网络状态为例来阐述】
原理:
我们定义一个Service,在该Service中设置一个定时器Timer,通过TimerTask的策略来检查当前应用的网络连接状态,关键是在该Service需要自定义一个回调接口用于向我们的Activity来回调发送网络状态,然后通过Bind来绑定当前的Service,在绑定成功之后得到回调信息
代码:
Service类
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 { @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return netBind; } //上下文 Context context; //网络连接状态 boolean isConntect = true; //定时器 Timer timer = new Timer(); @Override public void onCreate() { // 注册广播 检查网络状态 IntentFilter filter = new IntentFilter(); filter.addAction( ConnectivityManager.CONNECTIVITY_ACTION ); registerReceiver( receiver, filter ); Log.i( "tag", "service**"+Thread.currentThread().getId() ); super.onCreate(); } //网络检查广播接受者 private BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); // 启动定时任务 if (action.equals( ConnectivityManager.CONNECTIVITY_ACTION )) { //立即启动,每隔5秒执行一次Task Log.i( "tag", "receiver**"+Thread.currentThread().getId() ); timer.schedule( new NetTask( context ), 0, 5*1000 ); } } }; //具体的TimerTask实现类 class NetTask extends TimerTask { public NetTask(Context context1) { context = context1; } @Override public void run() { try { Thread.sleep( 20*1000 ); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (isConnectNet()) { isConntect = true; } else { isConntect = false; } Log.i( "tag", "run**"+Thread.currentThread().getId() ); if (onGetConnectState != null) { onGetConnectState.GetState( isConntect ); // 通知网络状态改变 } } } // 网络状态改变之后,通过此接口的实例通知当前网络的状态,此接口在Activity中注入实例对象 public interface GetConnectState { public void GetState(boolean isConnected); } private GetConnectState onGetConnectState; public void setOnGetConnectState(GetConnectState onGetConnectState) { this.onGetConnectState = onGetConnectState; } /** * 判断是否连通网络 * @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; } //定义一个Bind类 private NetBind netBind = new NetBind(); class NetBind extends Binder { public NetService getNetService() { return NetService.this; } } //销毁广播、停止定时轮询 @Override public void onDestroy() { // TODO Auto-generated method stub super.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; @Override protected 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; @Override public void onClick(View v) { switch (v.getId()) { case R.id.button1: // 绑定服务 Log.i( "tag", "click**" + Thread.currentThread().getId() ); Intent intent = new Intent( activity, NetService.class ); boolean isTrue = bindService( intent, conn, Context.BIND_AUTO_CREATE ); is = isTrue; break; case R.id.button2: unBind(); default: break; } } private void unBind() { if (conn != null) { unbindService( conn ); } } private boolean conncetState = true; private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceDisconnected(ComponentName name) { // TODO Auto-generated method stub } @Override public void onServiceConnected(ComponentName name, IBinder service) { NetBind bind = (NetBind) service; NetService netService = bind.getNetService(); //此处回调 netService.setOnGetConnectState( new GetConnectState() { @Override public void GetState(boolean isConnected) { // TODO Auto-generated method stub if (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(); default: break; } }; }; }
androi之Service+Broadcast+Timer+ui【通过绑定服务、自定义回调接口判断
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。