介绍:
通过 extends Service 创建自定义的服务。
通过 oncreate 中init 实例化参数。
首先检测网络是否连接,通过 wifi和有线连接两种检测。
检测到有网络,不管哪种,然后开始 ping 服务器或IP。
implements Runnable 中实现调用ping的方法,
Thread 来开始Runnable 运行。
Runnable 中通过无限循环实现连续ping,通过检测变量resOK,来停止runtime。
ping 过程中,连续记录ping 10次,
获取到的类似结构字符,
64 bytes from 14.215.177.38: icmp_seq=3 ttl=56 time=7.72 ms
检测该样式的字符判断成功与否。
package com.androidtest;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
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.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class MyService extends Service {
private static final String TAG = "MyService";
private boolean flashdebug =true;
private HandlerThread requestTimeThread;
private Handler mHandler;
private boolean register = false;
private ConnectivityManager mConnectivityManager;
private final int No_Ethernet=0;
private final int No_Wifinet=1;
private final int Network_Changed=2;
private final int Flashing=3;
private final int StopFlash=4;
private boolean resOK = false;
private int test_OK = 1;
private int test_ERROE = 0;
private Context mContext;
private ServiceRunnableProcess serProcess;
private Thread thProcess;
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG,"MyService--onCreate()");
if ( requestTimeThread == null ) {
init();
}
}
@Override
public void onDestroy() {
Log.d(TAG,"MyService--onDestroy()");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.d(TAG,"MyService--onBind()");
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG,"MyService--onStartCommand()");
return super.onStartCommand(intent, flags, startId);
}
private void init() {
mContext = MyService.this;
mConnectivityManager = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
requestTimeThread = new HandlerThread("MyService");
requestTimeThread.start();
mHandler = new Handler(requestTimeThread.getLooper());
serProcess = new ServiceRunnableProcess();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
filter.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
filter.addAction(WifiManager.RSSI_CHANGED_ACTION);
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
//filter.addAction(Intent.ACTION_BOOT_COMPLETED);
this.registerReceiver(mReceiver, filter);
if(!getWifiState() && !getEthernetState()){
mHandler.removeCallbacks(mSyncRunnable);
mHandler.post(mSyncRunnable);
}else{
mHandler.removeCallbacks(mSyncRunnable);
}
}
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.d(TAG,"LedService--onReceive="+action);
if(intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)
|| intent.getAction().equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
msgHandler.removeMessages(Network_Changed);
msgHandler.sendEmptyMessageDelayed(Network_Changed,2000);
}
}
};
Handler msgHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int what = msg.what;
if(what == Network_Changed){
msgHandler.removeMessages(Network_Changed);
if(!getEthernetState() && !getWifiState()){
msgHandler.sendEmptyMessage(Flashing);
}else{
Log.d(TAG,"need ping service");
resOK = false;
if(thProcess==null){
thProcess = new Thread(serProcess);
thProcess.start();
}
}
}
if(what == StopFlash){
Log.e(TAG, "StopFlash" );
if(thProcess !=null) {
thProcess.interrupt();
thProcess=null;
Log.e(TAG, "stop thProcess" );
}
mHandler.removeCallbacks(mSyncRunnable);
}
if(what == Flashing){
Log.e(TAG, "Flashing" );
if(!mHandler.hasCallbacks(mSyncRunnable)){
mHandler.post(mSyncRunnable);
}
}
}
};
private Runnable mSyncRunnable = new Runnable(){
@Override
public void run() {
//xxxxxx
Log.e(TAG, "mSyncRunnable do something" );
mHandler.postDelayed(this,800);
}
};
private boolean getWifiState(){
NetworkInfo mWiFiNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (mWiFiNetworkInfo != null && mWiFiNetworkInfo.isConnected()) {
if(flashdebug)Log.d(TAG,"wifi Connected");
return mWiFiNetworkInfo.isAvailable();
}else{
if(flashdebug)Log.d(TAG,"wifi Not Connected");
return false;
}
}
private boolean getEthernetState(){
NetworkInfo mNetworkInfo = mConnectivityManager.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);
if (mNetworkInfo != null && mNetworkInfo.isConnected()) {
if(flashdebug)Log.d(TAG,"Ethernet Connected");
return mNetworkInfo.isAvailable();
}else{
if(flashdebug)Log.d(TAG,"Ethernet not Connected");
return false;
}
}
class ServiceRunnableProcess implements Runnable{
@Override
public void run() {
Log.e(TAG, "ServiceRunnableProcess resOK:"+resOK);
while (!resOK) {
pingCustomerServer();
}
}
}
private void pingCustomerServer(){
String line = null;
BufferedReader buf = null;
Process pro = null;
Runtime runtime = null;
int count=0;
Log.e(TAG, "pingCustomerServer resOK:"+resOK);
try {
runtime = Runtime.getRuntime();
pro = runtime.exec("ping www.baidu.com");
buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
while ((line = buf.readLine()) != null) {
if (flashdebug) Log.e(TAG, "count="+ count +" line=" + line);
if(count >=10){
if(line.contains("icmp_seq=") && line.contains("ttl=")){
Log.e(TAG, "find string runtime stop" );
msgHandler.sendEmptyMessage(StopFlash);
resOK = true;
break;
}else{
msgHandler.sendEmptyMessage(Flashing);
resOK = false;
break;
}
}
count ++ ;
}
if(((line = buf.readLine()) == null)){
Log.e(TAG, "unable to connect" );
resOK = false;
msgHandler.sendEmptyMessage(Flashing);
}
}catch (Exception e){
Log.d(TAG,"find error:"+e.toString());
resOK = false;
}finally {
try {
buf.close();
pro.destroy();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}