記錄:AsyncTask后臺服務ping網(wǎng)絡檢測

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過程斷掉后又連上網(wǎng)絡,會出想超過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 返回的數(shù)據(jù)格式
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
//這里連續(xù)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;
最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容