最近项目要定时从服务器获取某些信息,通过研究来总结一下下【我以定时判断网络状态为例来阐述】
原理:
我们定义一个Service,在该Service中设置一个定时器Timer,通过TimerTask的策略来检查当前应用的网络连接状态,关键是在该Service需要自定义一个回调接口用于向我们的Activity来回调发送网络状态,然后通过Bind来绑定当前的Service,在绑定成功之后得到回调信息
代码:
Service类
[java]
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 inte易做图ce GetConnectState
{
public void GetState(boolean isConnected);
}
private GetConnectState onGetConnectState;
public void setOnGetConnectState(GetConnectState onGetConnectState)
{
this.onGetConnectState = onGetConnectState;
}
/**
* 判断是否连通网络
* @return
*/