iam*_*eyb 204 networking android android-networking
我想创建一个使用互联网的应用程序,我正在尝试创建一个检查连接是否可用的功能,如果不可用,请转到具有重试按钮和解释的活动.
附件是我的代码到目前为止,但我收到了错误 Syntax error, insert "}" to complete MethodBody.
现在我一直把这些放在试图让它工作,但到目前为止没有运气...任何帮助将不胜感激.
public class TheEvoStikLeagueActivity extends Activity {
private final int SPLASH_DISPLAY_LENGHT = 3000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
private boolean checkInternetConnection() {
ConnectivityManager conMgr = (ConnectivityManager) getSystemService (Context.CONNECTIVITY_SERVICE);
// ARE WE CONNECTED TO THE NET
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
return true;
/* New Handler to start the Menu-Activity
* and close this Splash-Screen after some seconds.*/
new Handler().postDelayed(new Runnable() {
public void run() {
/* Create an Intent that will start the Menu-Activity. */
Intent mainIntent = new Intent(TheEvoStikLeagueActivity.this, IntroActivity.class);
TheEvoStikLeagueActivity.this.startActivity(mainIntent);
TheEvoStikLeagueActivity.this.finish();
}
}, SPLASH_DISPLAY_LENGHT);
} else {
return false;
Intent connectionIntent = new Intent(TheEvoStikLeagueActivity.this, HomeActivity.class);
TheEvoStikLeagueActivity.this.startActivity(connectionIntent);
TheEvoStikLeagueActivity.this.finish();
}
}
}
Run Code Online (Sandbox Code Playgroud)
Ses*_*nay 394
此方法检查移动设备是否连接到互联网并在连接时返回true:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
Run Code Online (Sandbox Code Playgroud)
在清单中,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)
编辑: 此方法实际检查设备是否连接到互联网(有可能它连接到网络但不连接到互联网).
public boolean isInternetAvailable() {
try {
InetAddress ipAddr = InetAddress.getByName("google.com");
//You can replace it with your name
return !ipAddr.equals("");
} catch (Exception e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
Jar*_*ows 73
检查以确保它"连接"到网络:
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
Run Code Online (Sandbox Code Playgroud)
检查以确保它"连接"到网络:
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
需要许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)
raz*_*zak 52
你可以简单地ping一个谷歌在线网站:
public boolean isConnected() throws InterruptedException, IOException {
final String command = "ping -c 1 google.com";
return Runtime.getRuntime().exec(command).waitFor() == 0;
}
Run Code Online (Sandbox Code Playgroud)
Bha*_*eri 26
当您连接到Wi-Fi源或通过手机数据包时,上述方法可以正常工作.但是在Wi-Fi连接的情况下,有些情况下您会被要求在Cafe中登录.因此,在这种情况下,当您连接到Wi-Fi源而不是Internet时,您的应用程序将会失败.
这种方法很好.
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (IOException e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
请在主线程的单独线程中使用它,因为它进行网络调用,如果不遵循则会抛出NetwrokOnMainThreadException.
并且也不要将此方法放在onCreate或任何其他方法中.把它放在一个类中并访问它.
Pra*_*ani 22
您可以使用以下代码段来检查Internet连接.
无论是哪种方式,您都可以检查哪种类型的NETWORK Connection可用,这样您就可以通过这种方式完成流程.
您只需复制以下类并直接粘贴到您的包中即可.
/**
* @author Pratik Butani
*/
public class InternetConnection {
/**
* CHECK WHETHER INTERNET CONNECTION IS AVAILABLE OR NOT
*/
public static boolean checkConnection(Context context) {
final ConnectivityManager connMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connMgr != null) {
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
// connected to the mobile provider's data plan
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else return activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
}
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
现在你可以使用:
if (InternetConnection.checkConnection(context)) {
// Its Available...
} else {
// Not Available...
}
Run Code Online (Sandbox Code Playgroud)
不要忘记取得许可:) :)
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Run Code Online (Sandbox Code Playgroud)
您可以根据您的要求进行修改.
谢谢.
Han*_*ans 17
接受的答案的编辑显示了如何检查是否可以访问互联网上的内容.如果不是这样的话,我不得不等待太久的答案(没有互联网连接的wifi).不幸的是InetAddress.getByName没有超时参数,所以下一个代码可以解决这个问题:
private boolean internetConnectionAvailable(int timeOut) {
InetAddress inetAddress = null;
try {
Future<InetAddress> future = Executors.newSingleThreadExecutor().submit(new Callable<InetAddress>() {
@Override
public InetAddress call() {
try {
return InetAddress.getByName("google.com");
} catch (UnknownHostException e) {
return null;
}
}
});
inetAddress = future.get(timeOut, TimeUnit.MILLISECONDS);
future.cancel(true);
} catch (InterruptedException e) {
} catch (ExecutionException e) {
} catch (TimeoutException e) {
}
return inetAddress!=null && !inetAddress.equals("");
}
Run Code Online (Sandbox Code Playgroud)
所有官方方法仅告知设备是否为网络开放,
如果您的设备连接到Wifi但Wifi没有连接到互联网,那么这些方法将失败(这种情况很多次发生),没有内置网络检测方法会告诉您这一点场景,所以创建了Async Callback类,它将在onConnectionSuccess和onConnectionFail中返回
new CheckNetworkConnection(this, new CheckNetworkConnection.OnConnectionCallback() {
@Override
public void onConnectionSuccess() {
Toast.makeText(context, "onSuccess()", toast.LENGTH_SHORT).show();
}
@Override
public void onConnectionFail(String msg) {
Toast.makeText(context, "onFail()", toast.LENGTH_SHORT).show();
}
}).execute();
Run Code Online (Sandbox Code Playgroud)
来自异步任务的网络呼叫
public class CheckNetworkConnection extends AsyncTask<Void, Void, Boolean> {
private OnConnectionCallback onConnectionCallback;
private Context context;
public CheckNetworkConnection(Context con, OnConnectionCallback onConnectionCallback) {
super();
this.onConnectionCallback = onConnectionCallback;
this.context = con;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected Boolean doInBackground(Void... params) {
if (context == null)
return false;
boolean isConnected = new NetWorkInfoUtility().isNetWorkAvailableNow(context);
return isConnected;
}
@Override
protected void onPostExecute(Boolean b) {
super.onPostExecute(b);
if (b) {
onConnectionCallback.onConnectionSuccess();
} else {
String msg = "No Internet Connection";
if (context == null)
msg = "Context is null";
onConnectionCallback.onConnectionFail(msg);
}
}
public interface OnConnectionCallback {
void onConnectionSuccess();
void onConnectionFail(String errorMsg);
}
}
Run Code Online (Sandbox Code Playgroud)
将ping到服务器的实际类
class NetWorkInfoUtility {
public boolean isWifiEnable() {
return isWifiEnable;
}
public void setIsWifiEnable(boolean isWifiEnable) {
this.isWifiEnable = isWifiEnable;
}
public boolean isMobileNetworkAvailable() {
return isMobileNetworkAvailable;
}
public void setIsMobileNetworkAvailable(boolean isMobileNetworkAvailable) {
this.isMobileNetworkAvailable = isMobileNetworkAvailable;
}
private boolean isWifiEnable = false;
private boolean isMobileNetworkAvailable = false;
public boolean isNetWorkAvailableNow(Context context) {
boolean isNetworkAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
setIsWifiEnable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnected());
setIsMobileNetworkAvailable(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnected());
if (isWifiEnable() || isMobileNetworkAvailable()) {
/*Sometime wifi is connected but service provider never connected to internet
so cross check one more time*/
if (isOnline())
isNetworkAvailable = true;
}
return isNetworkAvailable;
}
public boolean isOnline() {
/*Just to check Time delay*/
long t = Calendar.getInstance().getTimeInMillis();
Runtime runtime = Runtime.getRuntime();
try {
/*Pinging to Google server*/
Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
int exitValue = ipProcess.waitFor();
return (exitValue == 0);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
long t2 = Calendar.getInstance().getTimeInMillis();
Log.i("NetWork check Time", (t2 - t) + "");
}
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
不需要复杂.最简单的框架方式是使用ACCESS_NETWORK_STATE权限并只创建一个连接的方法
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
Run Code Online (Sandbox Code Playgroud)
requestRouteToHost如果您有特定的主机和连接类型(wifi /移动),您也可以使用.
您还需要:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)
在你的Android清单中.
更多细节请到这里
使用此方法:
public static boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
Run Code Online (Sandbox Code Playgroud)
这是需要的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Run Code Online (Sandbox Code Playgroud)
尝试以下代码:
public static boolean isNetworkAvailable(Context context) {
boolean outcome = false;
if (context != null) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = cm.getAllNetworkInfo();
for (NetworkInfo tempNetworkInfo : networkInfos) {
/**
* Can also check if the user is in roaming
*/
if (tempNetworkInfo.isConnected()) {
outcome = true;
break;
}
}
}
return outcome;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
314904 次 |
| 最近记录: |