如何使用GDK检查Google Glass是否已连接到互联网

Ton*_*ham 3 google-glass google-gdk

有没有办法检测Google Glass是否在运行时连接到互联网?例如,在我的应用中使用语音输入时,我经常收到"无法立即访问Google"的消息.相反,我想先发制人地拦截导致该消息并使用默认值而不是要求语音输入的条件.在搜索了一段时间之后,我唯一能找到的就是针对Android的相同问题的解决方案:

private boolean isConnected() {
    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Run Code Online (Sandbox Code Playgroud)

我尝试将它用于我的Glassware但它似乎不起作用(我关闭了wifi和数据,但isConnected()仍然返回true,即使我得到"无法立即到达Google"消息).有谁知道GDK是否有办法做到这一点?或者应该类似于上述方法的工作?

编辑:这是我最终的解决方案,部分基于下面的EntryLevelDev的答案.

我不得不使用后台线程来使用HTTP GET请求以避免获得NetworkOnMainThreadException,因此我决定让它每隔几秒运行一次并更新本地isConnected变量:

public static boolean isConnected = false;

public boolean isDeviceConnectedToInternet() {
    return isConnected;
}

private class CheckConnectivityTask extends AsyncTask<Void, Boolean, Boolean> {
    protected Boolean doInBackground(Void... voids) {
        while(true) {
            // Update isConnected variable.
            publishProgress(isConnected());
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Determines if the Glassware can access the internet.
     * isNetworkAvailable() is used first because there is no point in executing an HTTP GET
     * request if ConnectivityManager and NetworkInfo tell us that no network is available.
     */
    private boolean isConnected(){
        if (isNetworkAvailable()) {
            HttpGet httpGet = new HttpGet("http://www.google.com");
            HttpParams httpParameters = new BasicHttpParams();
            HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
            HttpConnectionParams.setSoTimeout(httpParameters, 5000);

            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            try{
                Log.d(LOG_TAG, "Checking network connection...");
                httpClient.execute(httpGet);
                Log.d(LOG_TAG, "Connection OK");
                return true;
            }
            catch(ClientProtocolException e){
                e.printStackTrace();
            }
            catch(IOException e){
                e.printStackTrace();
            }
            Log.d(LOG_TAG, "Connection unavailable");
        } else {
            // No connection; for Glass this probably means Bluetooth is disconnected.
            Log.d(LOG_TAG, "No network available!");
        }
        return false;
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager
                = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        Log.d(LOG_TAG, String.format("In isConnected(), activeNetworkInfo.toString(): %s",
                activeNetworkInfo == null ? "null" : activeNetworkInfo.toString()));
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    protected void onProgressUpdate(Boolean... isConnected) {
        DecisionMakerService.isConnected = isConnected[0];
        Log.d(LOG_TAG, "Checking connection: connected = " + isConnected[0]);
    }
}
Run Code Online (Sandbox Code Playgroud)

要启动它,请调用new CheckConnectivityTask().execute();(可能来自onCreate()).我还必须将这些添加到我的Android.manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)

pt2*_*121 5

如果Glass连接到带蓝牙的手机,即使手机没有WiFi和数据连接,您的方法也会返回true.

我想这是一个正确的行为.getActiveNetworkInfo更多是关于通过可用接口的连接.这不是关于互联网的连接.这就像连接到路由器并不意味着你连接到互联网.

注意(来自文档):

getActiveNetworkInfo返回

"当前默认网络的NetworkInfo对象;如果当前没有网络默认网络,则为null"

要检查互联网连接,您可以尝试ping Google,但我认为可能有更好的方法来检查.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    new Thread(new Runnable() {

        @Override
        public void run() {
            Log.v(MainActivity.class.getSimpleName(), "isGoogleReachable : "
                    + isGoogleReachable());
        }

    }).start();;

}
private boolean isGoogleReachable() {
    try {
        if (InetAddress.getByName("www.google.com").isReachable(5000)) {
            return true;
        } else {
            return false;
        }
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return false;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加此权限:

<uses-permission android:name="android.permission.INTERNET" />
Run Code Online (Sandbox Code Playgroud)

编辑:或者你可以试试这个:

public static void isNetworkAvailable(Context context){
    HttpGet httpGet = new HttpGet("http://www.google.com");
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    // The default value is zero, that means the timeout is not used.
    int timeoutConnection = 3000;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = 5000;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    try{
        Log.d(TAG, "Checking network connection...");
        httpClient.execute(httpGet);
        Log.d(TAG, "Connection OK");
        return;
    }
    catch(ClientProtocolException e){
        e.printStackTrace();
    }
    catch(IOException e){
        e.printStackTrace();
    }

    Log.d(TAG, "Connection unavailable");
}
Run Code Online (Sandbox Code Playgroud)

另见:

检测Android设备是否具有Internet连接

"应该类似于上述方法吗?"

是的,如果蓝牙也关闭,它可以正常工作.