记录:AsyncTask后台服务ping网络检测

private boolean DEBUG = true;
private Runtime runtime = null;
private Context context;
private int RES_OK = 100;
private int RES_ERROE = 101;
private boolean resOK = false;
private int test_OK = 1;
private int test_ERROE = 0;
private Handler flashhandler = new Handler();
private MyTask mtask;

protected void onResume() {
    super.onResume();
    mtask = new MyTask();
    mtask.execute();
}

//在异步开机线程来测试ping,不然会阻塞ui线程
private class MyTask extends AsyncTask<String, Integer, Void>{
    @Override
    protected Void doInBackground(String... params) {
        while(true) {
            pingCustomerServer();
            try {
                Thread.sleep(13*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


private boolean pingCustomerServer(){
    String line = null;
    BufferedReader buf = null;
    Process pro = null;
    int count=0;

   //自定义的标志
    resOK = Settings.System.getInt(context.getContentResolver(), "network.customer.service", test_ERROE) == test_OK?true:false;
    Log.e("testFlash", "pingCustomerServer resOK:"+resOK);
    if(resOK) {
        if(runtime!=null) runtime.exit(0);
        runtime = null;
    }else {
        if(runtime == null){
            runtime = Runtime.getRuntime();
        }
    }

  //在ping过程中可能会断掉,这个时候测试的buf就是空的
  //在ping过程断掉后又连上网络,会出想超过10次的情况

    if(!resOK) {
        try {
            pro = runtime.exec("ping www.baidu.com");
            buf = new BufferedReader(new InputStreamReader(
                    pro.getInputStream()));
            while ((line = buf.readLine()) != null) {
                if (DEBUG) Log.e("testFlash", "count="+ count +" line=" + line);
                if(count >= 10) {
                    Log.e("testFlash", "checkResult connect =10" );
                    if(checkResult(line)) {
                        Log.e("testFlash", "checkResult OK" );
                        resOK = true;
                        Settings.System.putInt(context.getContentResolver(), "network.customer.service", test_OK);
                        handler.sendEmptyMessage(RES_OK);
                        return true;
                    }else{
                        handler.sendEmptyMessage(FLASH_LED);
                        return false;
                    }
                }
                else {
                    if(count > 10) {
                        if(checkResult(line)) {
                            Log.e("testFlash", "checkResult connect >10" );
                             //这里能停止runtime
                            runtime.exit(0);
                            runtime = null;
                            resOK = true;
                            Settings.System.putInt(context.getContentResolver(), "network.customer.service", test_OK);
                            handler.sendEmptyMessage(RES_OK);
                            return true;
                        }else{
                            handler.sendEmptyMessage(FLASH_LED);
                            return false;
                        }
                    }
                }
                count ++ ;
            }

            if(((line = buf.readLine()) == null)){
                Log.e("testFlash", "unable to connect" );
                handler.sendEmptyMessage(FLASH_LED);
                return false;
            }
        }catch (Exception e){
            Log.d("testFlash","Exception:"+e.toString());
            return false;
        }finally {
            try {
                buf.close();
                pro.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return false;
        }
    }
    return false;
}

ping 返回的数据格式
from 14.215.177.38: icmp_seq=1 ttl=54 time=7.73 ms
from 14.215.177.38: icmp_seq=2 ttl=54 time=7.47 ms
from 14.215.177.38: icmp_seq=3 ttl=54 time=7.65 ms
//这里连续10次后检测结果
private boolean checkResult(String line){
    /*String strs[] = line.split(" ");
    for(int i=0;i < strs.length;i++){
        Log.d("getstr","string:"+strs[i]);
    }
    String strCount = strs[4];//"icmp_seq=10"
    Log.d("getstr","find the str:"+strCount);
    String counts[] = strCount.split("=");
    int num = Integer.parseInt(counts[1]);
    if(num >= 10){
        Log.d("getstr","find the count:"+num);
        return true;
    }else {
        return false;
    }*/

     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 ++ ;
      return resOK ;
}

//检测成功后停止 后台
mtask.cancel(true); 
//同时停止runtime,不然会一直在后台
runtime.exit(0);
runtime=null;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容