如何使用GDK检查Google Glass是否已连接到互联网 [英] How to check if Google Glass is connected to internet using GDK

查看:64
本文介绍了如何使用GDK检查Google Glass是否已连接到互联网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以在运行时检测Google Glass是否已连接到互联网?例如,在我的应用中使用语音输入时,我经常收到现在无法访问Google"消息.相反,我想抢先拦截将导致该消息的条件,并使用默认值,而不是要求语音输入.搜索了一会儿之后,我唯一能找到的就是一般情况下针对Android的同一问题的解决方案:

Is there a way to detect if Google Glass is connected to the internet at runtime? For instance, I often get the message "Can't reach Google right now" when using voice input in my app. Instead, I would like to preemptively intercept the condition that would cause that message and use default values rather than ask for voice input. After searching for a while, the only thing I could find was a solution to the same question for Android in general:

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

我曾尝试将其用于我的Glassware,但似乎无法正常工作(我关闭了wifi和数据,但即使我收到目前无法访问Google"消息,isConnected()仍返回true).有谁知道GDK是否有办法做到这一点?还是应该使用类似于上述方法的方法?

I tried using this for my Glassware but it doesn't seem to work (I turned off the wifi and data but isConnected() still returns true even though I get the "Can't reach Google right now" message). Does anyone know if the GDK has a way to do this? Or should something similar to the above method work?

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

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

I had to use a background thread to use HTTP GET requests to avoid getting a NetworkOnMainThreadException, so I decided to have it run every few seconds and update a local isConnected variable:

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]);
    }
}

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

To start it, call new CheckConnectivityTask().execute(); (probably from onCreate()). I also had to add these to my Android.manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

推荐答案

如果Glass通过蓝牙连接到电话,即使您的电话没有WiFi和数据连接,您的方法也会返回true.

If Glass connects to a phone with Bluetooth, your method returns true even when your phone has no WiFi and data connection.

我猜这是正确的行为. getActiveNetworkInfo 有关通过可用接口进行连接的更多信息.这实际上与互联网连接无关.就像连接路由器并不意味着您已连接到互联网.

I guess it's a correct behavior. getActiveNetworkInfo is more about a connection via available interfaces. It's not really about connection to the internet. It's like connecting to a router doesn't mean you connect to the internet.

注意(

getActiveNetworkInfo返回

getActiveNetworkInfo returns

当前默认网络的NetworkInfo对象;如果当前没有网络默认网络处于活动状态,则为null"

"a NetworkInfo object for the current default network or null if no network default network is currently active"

要检查Internet连接,您可以尝试ping Google,尽管我认为可能有更好的检查方法.

To check the internet connection, you might try ping Google instead though I think there might be a better way to check.

@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;
    }
}

添加此权限:

<uses-permission android:name="android.permission.INTERNET" />

或者,您可以尝试:

Or you could try this:

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");
}

另请参见:

检测Android设备是否可以连接互联网

与上述方法类似的东西应该起作用吗?"

"should something similar to the above method work?"

是的,如果蓝牙也处于关闭状态,则可以正常工作.

Yes, it works fine if Bluetooth is also off.

这篇关于如何使用GDK检查Google Glass是否已连接到互联网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆