有没有办法检测Google Glass是否在运行时连接到互联网?例如,在我的应用中使用语音输入时,我经常收到“无法立即访问Google”的消息。相反,我想先发制人地拦截导致该消息并使用默认值而不是要求语音输入的条件。在搜索了一段时间之后,我唯一能找到的就是针对Android的相同问题的解决方案:
private boolean isConnected() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
我尝试将它用于我的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]);
}
}
要启动它,请调用new CheckConnectivityTask().execute();
(可能来自onCreate())。我还必须将这些添加到我的Android.manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
答案 0 :(得分:5)
如果Glass连接到带蓝牙的手机,即使手机没有WiFi和数据连接,您的方法也会返回true。
我猜这是正确的行为。 getActiveNetworkInfo 更多的是通过可用接口建立连接。这不是关于互联网的连接。这就像连接到路由器并不意味着你连接到互联网。
注意(from the doc):
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;
}
}
添加此权限:
<uses-permission android:name="android.permission.INTERNET" />
修改: 或者您可以尝试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");
}
另见:
Detect if Android device has Internet connection
“应该与上述方法类似吗?”
是的,如果蓝牙也关闭,它可以正常工作。
答案 1 :(得分:0)
当您关闭wifi和数据时,activeNetworkInfo.getTypeName()
返回的网络类型名称是什么?
这可能是一个错误 - 您可以从NetworkInfo
对象(特别是类型名称,DetailedState
枚举等)中尽可能多地转储信息,并将其存入我们的{{ 3}}?