Android 检查programm是否通过wifi连接互联网
在阅读了一些答案并尝试使用它们之后,我仍然无法使我的代码返回正确的状态,无论是否有通过wifi的互联网 我必须通过WIFI“ping”,因为我们可能连接到接入点,而无需进一步的互联网连接。这是一个完整的代码Android 检查programm是否通过wifi连接互联网,android,android-wifi,Android,Android Wifi,在阅读了一些答案并尝试使用它们之后,我仍然无法使我的代码返回正确的状态,无论是否有通过wifi的互联网 我必须通过WIFI“ping”,因为我们可能连接到接入点,而无需进一步的互联网连接。这是一个完整的代码 ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo NI = CM.getActiveNetworkInfo()
ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
boolean IC = false;
IC = CM.requestRouteToHost(ConnectivityManager.TYPE_WIFI, FlavaGr.lookupHost(pingyIp));
System.out.println("##### IC=" + IC + " TYPE = " + NI.getTypeName());
此处是lookupHost,由另一个用户建议:
public static int lookupHost(String hostname) {
InetAddress inetAddress;
try {
inetAddress = InetAddress.getByName(hostname);
} catch (UnknownHostException e) {
return -1;
}
byte[] addrBytes;
int addr;
addrBytes = inetAddress.getAddress();
addr = ((addrBytes[3] & 0xff) << 24)
| ((addrBytes[2] & 0xff) << 16)
| ((addrBytes[1] & 0xff) << 8)
| (addrBytes[0] & 0xff);
return addr;
}
publicstaticintlookuphost(字符串主机名){
InetAddress InetAddress;
试一试{
inetAddress=inetAddress.getByName(主机名);
}捕获(未知后异常e){
返回-1;
}
字节[]加上字节;
国际地址;
addrBytes=inetAddress.getAddress();
addr=((addrBytes[3]&0xff)这是我使用的代码,它可以正常工作:
ConnectivityManager conn;
conn=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Skip if no connection, or background data disabled
NetworkInfo info = conn.getActiveNetworkInfo();
if (info == null ||
!conn.getBackgroundDataSetting()) {
// No Network detected
return;
} else {
int netType = info.getType();
int netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
//WIFI DETECTED
} else if (netType == ConnectivityManager.TYPE_MOBILE
&& netSubtype >2) {
//Mobile connected that is at least 3G
} else {
//Has connection but i'm not sure what kind
}
}
在我的舱单中:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
请注意,在模拟计算机上,检测到的internet连接可能会出现异常行为。这是我使用的代码,它可以正常工作:
ConnectivityManager conn;
conn=(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Skip if no connection, or background data disabled
NetworkInfo info = conn.getActiveNetworkInfo();
if (info == null ||
!conn.getBackgroundDataSetting()) {
// No Network detected
return;
} else {
int netType = info.getType();
int netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
//WIFI DETECTED
} else if (netType == ConnectivityManager.TYPE_MOBILE
&& netSubtype >2) {
//Mobile connected that is at least 3G
} else {
//Has connection but i'm not sure what kind
}
}
在我的舱单中:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
请注意,在模拟计算机上,检测到的internet连接可能会出现异常行为。尝试此方法以检查是否存在internet连接:
public boolean connexionStatus(ConnectivityManager connec)
{
NetworkInfo[] allNetwork = connec.getAllNetworkInfo();
if (allNetwork != null)
{
for (int i = 0; i < allNetwork.length; i++)
{
if (allNetwork[i].getState() == NetworkInfo.State.CONNECTED ||
allNetwork[i].getState() == NetworkInfo.State.CONNECTING )
return true;
}
}
return false;
}
public boolean连接状态(ConnectivityManager connec)
{
NetworkInfo[]allNetwork=connec.getAllNetworkInfo();
if(所有网络!=null)
{
for(int i=0;i
注意:您应该在您的清单中拥有INTERNET的权限尝试此方法检查是否有INTERNET连接:
public boolean connexionStatus(ConnectivityManager connec)
{
NetworkInfo[] allNetwork = connec.getAllNetworkInfo();
if (allNetwork != null)
{
for (int i = 0; i < allNetwork.length; i++)
{
if (allNetwork[i].getState() == NetworkInfo.State.CONNECTED ||
allNetwork[i].getState() == NetworkInfo.State.CONNECTING )
return true;
}
}
return false;
}
public boolean连接状态(ConnectivityManager connec)
{
NetworkInfo[]allNetwork=connec.getAllNetworkInfo();
if(所有网络!=null)
{
for(int i=0;i
注意:您应该在您的清单中获得互联网的许可我的答案是:
ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
if (NI!=null) {
if (NI.isAvailable()) {
boolean IC = false;
if (NI.getTypeName()=="WIFI") {
int response = 0;
try {
URL url = new URL("http://www.google.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
response = in.read();
in.close();
IC = (response != -1) ? true : false;
System.out.println("##### IC=" + IC + " TYPE = " + NI.getTypeName() + " response = " + response);
if (true){
;
};
} catch (Exception e) {
}}}}}
检查一下,如果当前连接是WIFI,然后请求一个页面,检查第一个字符。我的答案是:
ConnectivityManager CM = (ConnectivityManager) mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo NI = CM.getActiveNetworkInfo();
if (NI!=null) {
if (NI.isAvailable()) {
boolean IC = false;
if (NI.getTypeName()=="WIFI") {
int response = 0;
try {
URL url = new URL("http://www.google.com/");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
response = in.read();
in.close();
IC = (response != -1) ? true : false;
System.out.println("##### IC=" + IC + " TYPE = " + NI.getTypeName() + " response = " + response);
if (true){
;
};
} catch (Exception e) {
}}}}}
只是为了检查,如果当前连接是WIFI,然后请求一个页面,检查第一个字符。我成功了:)
首先,在主线程上执行httprequest是不允许的,也是不好的!所以您必须在AsyncTask中执行它
第二,您不需要检查是否有连接…因为您可以连接到本地连接或连接太慢
您只需执行http请求并检查在准确时间内是否有响应。为此,您需要设置超时!但只有超时不起作用-您需要检查状态代码…如下所示:
class ConnectionTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread set flag to false
* */
@Override
protected void onPreExecute() {
super.onPreExecute();
flag = false;
}
boolean flag;
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
Log.v("url",url);
JSONObject json = jParser.makeHttpRequest(url, "GET", params);
/*is json equal to null ?*/
if( json != null )
{
// Check your log cat for JSON response
Log.d("json: ", json.toString());
try {
message = json.getString("message");
flag = true;//we succeded so we make the flag to true
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{//if json is null
message = "not connected to internet connection";
flag = false;
}
return null;
}
/**
* After completing background task check if there is connection or no
* **/
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
if(flag)
{//flag is tro so there is connection
Log.v("connection", "conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into textview
* */
TextView tvTest = (TextView) findViewById(R.id.testTextView);
tvTest.setText(message);
}
});
}
else
{////we catched that there is no connection!
Log.v("connection", "nooooooo conectioOOOOOoooOooooOoooooOOOOoooOOOOOO");
runOnUiThread(new Runnable() {
public void run() {
/*update ui thread*/
TextView tvTest = (TextView) findViewById(R.id.testTextView);
tvTest.setText("no connection");
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
});
}
}
}
类连接任务扩展异步任务{
/**
*在启动后台线程之前,请将标志设置为false
* */
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
flag=false;
}
布尔标志;
/**
*从url获取所有产品
* */
受保护的字符串doInBackground(字符串…args){
//建筑参数
List params=new ArrayList();
//从URL获取JSON字符串
Log.v(“url”,url);
JSONObject json=jParser.makeHttpRequest(url,“GET”,参数);
/*json是否等于null*/
if(json!=null)
{
//检查日志cat中的JSON响应
Log.d(“json:,json.toString());
试一试{
message=json.getString(“message”);
flag=true;//我们成功了,所以我们将标志设置为true
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
其他的
{//如果json为null
message=“未连接到internet连接”;
flag=false;
}
返回null;
}
/**
*完成后台任务后,检查是否存在连接
* **/
受保护的void onPostExecute(字符串文件\u url){
//从后台线程更新UI
国际单项体育联合会(旗)
{//标志是tro,因此存在连接
Log.v(“连接”、“连接”);
runOnUiThread(新的Runnable(){
公开募捐{
/**
*将解析的JSON数据更新到textview
* */
TextView tvTest=(TextView)findViewById(R.id.testTextView);
tvetest.setText(消息);
}
});
}
其他的
{///我们发现没有连接!
Log.v(“连接”,“无连接”);
runOnUiThread(新的Runnable(){
公开募捐{
/*更新ui线程*/
TextView tvTest=(TextView)findViewById(R.id.testTextView);
tvTest.setText(“无连接”);
Toast.makeText(getApplicationContext(),“无internet连接”,Toast.LENGTH_LONG.show();
}
});
}
}
}
现在json解析器:)
公共类JSONParser{
私有InputStream为空;
私有JSONObject jObj=null;
私有字符串json=“”;
静态int超时连接=10000;
静态int timeoutSocket=10000;
//建造师
公共JSONParser(){
}
//函数从中获取json