最近項目要定時從服務器獲取某些信息,通過研究來總結一下下【我以定時判斷網絡狀態為例來闡述】
原理:
我們定義一個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 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:
[java]
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;
}
};
};
}
PS:記得加網絡權限哦