我想创建一个使用互联网的应用程序,我试图创建一个功能,检查连接是否可用,如果它不是,去到一个活动,有一个重试按钮和解释。
附件是我的代码到目前为止,但我得到的错误语法错误,插入“}”来完成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();
}
}
}
这个方法检查手机是否连接到互联网,如果连接则返回true:
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected();
}
在清单,
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
编辑:
这个方法实际上是检查设备是否连接到互联网(有可能它连接到网络但没有连接到互联网)。
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;
}
}
检查以确保它“连接”到网络:
public boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE));
return connectivityManager.getActiveNetworkInfo() != null && connectivityManager.getActiveNetworkInfo().isConnected();
}
检查以确保它“连接”到互联网:
public boolean isInternetAvailable() {
try {
InetAddress address = InetAddress.getByName("www.google.com");
return !address.equals("");
} catch (UnknownHostException e) {
// Log error
}
return false;
}
需要许可:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
https://stackoverflow.com/a/17583324/950427
当您连接到Wi-Fi源或通过手机数据包时,上述方法都有效。但在Wi-Fi连接的情况下,有时你会被进一步要求登录,就像在咖啡馆一样。所以在这种情况下,你的应用程序将失败,因为你连接的是Wi-Fi源,而不是互联网。
这个方法很有效。
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;
}
请在与主线程分开的线程中使用此线程,因为它会进行网络调用,如果不遵循将抛出networkkonmainthreadexception。
也不要把这个方法放在onCreate或任何其他方法中。把它放到一个类中并访问它。
不需要太复杂。最简单的框架方式是使用ACCESS_NETWORK_STATE权限并创建一个连接的方法
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
如果您有特定的主机和连接类型(wifi/移动),也可以使用requestRouteToHost。
你还需要:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
在你的android清单中。
更多细节请点击这里
1-创建新的Java文件(右键单击包。新建>类>,命名为文件ConnectionDetector.java
2-在文件中添加以下代码
package <add you package name> example com.example.example;
import android.content.Context;
import android.net.ConnectivityManager;
public class ConnectionDetector {
private Context mContext;
public ConnectionDetector(Context context){
this.mContext = context;
}
public boolean isConnectingToInternet(){
ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected() == true)
{
return true;
}
return false;
}
}
3-打开MainActivity.java -要检查连接的活动,并执行以下操作
创建并定义函数。
ConnectionDetector mConnectionDetector;</pre>
在“OnCreate”中添加以下内容
mConnectionDetector = new ConnectionDetector(getApplicationContext());
C -检查连接使用以下步骤
if (mConnectionDetector.isConnectingToInternet() == false) {
//no connection- do something
} else {
//there is connection
}
检查网络可用在android与互联网数据速度。
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) Login_Page.this.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
try
{
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(500); //choose your own timeframe
urlc.setReadTimeout(500); //choose your own timeframe
urlc.connect();
int networkcode2 = urlc.getResponseCode();
return (urlc.getResponseCode() == 200);
} catch (IOException e)
{
return (false); //connectivity exists, but no internet.
}
}
}
return false;
}
此函数返回true或false。
必须获得用户权限
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
您可以使用以下代码片段检查Internet连接。
它将有用的两种方式,你可以检查哪种类型的网络
连接是可用的,因此您可以以这种方式执行流程。
你只需要复制下面的类,并直接粘贴在你的包。
/**
* @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;
}
}
现在你可以用like:
if (InternetConnection.checkConnection(context)) {
// Its Available...
} else {
// Not Available...
}
别忘了征求同意:)
<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" />
您可以根据自己的需求进行修改。
谢谢你!
所有的官方方法都只说明设备是否对网络开放,
如果你的设备连接到Wifi,但Wifi没有连接到互联网,那么这些方法会失败(发生了很多次),没有内置的网络检测方法会告诉这种情况,所以创建了Async回调类,它将在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();
异步任务的网络调用
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);
}
}
将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;
}
}