Androidはデバイスがネットワークに接続されているかどうかを検出します

2768 ワード

public class NetWorkStatusService extends Service {


    private static ScheduledExecutorService executor;

    @Override
    public void onCreate() {
        super.onCreate();
        executeFixedRate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    /**
     *            
     */
    public static void executeFixedRate() {
        executor = Executors.newScheduledThreadPool(1);
        executor.scheduleAtFixedRate(
                new EchoServer(),
                0,
                5,
                TimeUnit.SECONDS);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    static class EchoServer implements Runnable {
        @Override
        public void run() {
            if (NetUtils.ping()) {
                TApplication.isNetConnect = true;
            } else {
                TApplication.isNetConnect = false;
            }
            try {
                throw new RuntimeException();
            } catch (Exception e) {
                System.out.println("RuntimeException catched,can run next");
            }
            System.out.println("This is a echo server. The current time is " +
                    System.currentTimeMillis() + ".");
        }
    }

}
public class NetUtils {


    /* @author suncat
 * @category          (                 ,        )
 * @return
 */
    public static final boolean ping() {

        String result = null;
        try {
            String ip = "www.baidu.com";// ping    ,             
            Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping  3 
            //   ping   ,    
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.d("------ping-----", "result content : " + stringBuffer.toString());
            // ping   
            int status = p.waitFor();
            if (status == 0) {
                result = "success";
                return true;
            } else {
                result = "failed";
            }
        } catch (IOException e) {
            result = "IOException";
        } catch (InterruptedException e) {
            result = "InterruptedException";
        } finally {
            Log.d("----result---", "result = " + result);
        }
        return false;
    }

}