问题
I am working on a live project. and when user click on the app. the welcome screen appears(there is a webview on that screen). and if the internet is not connected then the app crashes. Basically, my problem is to check programmatically that is mobile is connected to internet or not. if not then don't fetch the data from webservice into webview and display a dialog box showing "Check your internet connection"
while doing research i found many things, and i have tried to implement that. but, its not satisfying my requirement
my code is,
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
else
{
Description.setVisibility(View.INVISIBLE);
new AlertDialog.Builder(WelcomePage.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(
getResources().getString(
R.string.internet_error))
.setPositiveButton("OK", null).show();
}
return false;
}
i am calling this function in doInBackground()
of AsyncTask
Please Help!
回答1:
You could checkout this library:
https://github.com/novoda/merlin
You just implement Connectable
and you will get a callback when the network goes down or comes up.
Therefore you can show your dialog in this scenario.
You can also query the library for the current state and choose not to do your network task
Create Merlin (using Merlin.Builder())
merlin = new Merlin.Builder().withConnectableCallbacks().build(context);
Bind and unbind the service in your activity
@Override
protected void onResume() {
super.onResume();
merlin.bind();
}
@Override
protected void onPause() {
super.onPause();
merlin.unbind();
}
Register for callbacks
merlin.registerConnectable(new Connectable() {
@Override
public void onConnect() {
// Do something!
}
});
The MerlinActivity within the demo shows a simple way to declutter Merlin from your main application code.
回答2:
Finally, I got the answer.
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if (netInfo == null){
Description.setVisibility(View.INVISIBLE);
new AlertDialog.Builder(WelcomePage.this)
.setTitle(getResources().getString(R.string.app_name))
.setMessage(getResources().getString(R.string.internet_error))
.setPositiveButton("OK", null).show();
}else{
dialog = ProgressDialog.show(WelcomePage.this, "", "Loading...", true,false);
new Welcome_Page().execute();
}
回答3:
Check internet connection
ConnectivityManager mgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = mgr.getActiveNetworkInfo();
if (netInfo != null) {
if (netInfo.isConnected()) {
// Internet Available
}else {
//No internet
}
} else {
//No internet
}
回答4:
This is simple function that check your Internet connection. If Connected return true otherwise false.
public boolean isInternetOn() {
// get Connectivity Manager object to check connection
ConnectivityManager connec =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// Check for network connections
if (connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED) {
return true;
} else if (
connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED) {
return false;
}
return false;
}
}
Here's a project that check internet connection and also check url that valid or contain in sever this.
回答5:
I've tried different methods described above, besides it I've been caught in some cases. So finally, I'm using below code snippet to make a network call...
try {
InetAddress address = InetAddress.getByName("www.stackoverflow.com");
//Connected to working internet connection
} catch (UnknownHostException e) {
e.printStackTrace();
//Internet not available
}
This can be useful in many perspectives. If something is not fine in this approach, please let me know.
回答6:
if (InternetConnection.checkConnection(context)) {
// Internet Available...
} else {
// Internet Not Available...
}
just copy below class
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);
NetworkInfo activeNetworkInfo = connMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null) { // connected to the internet
Toast.makeText(context, activeNetworkInfo.getTypeName(), Toast.LENGTH_SHORT).show();
if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
// connected to wifi
return true;
} else if (activeNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
// connected to the mobile provider's data plan
return true;
}
}
return false;
}
}
Give following permission to manifest
<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" />
回答7:
public boolean isOnline() {
NetworkInfo activeNetworkInfo = ((ConnectivityManager)
getSystemService(CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
return activeNetworkInfo != null &&
activeNetworkInfo.isConnectedOrConnecting();
}
回答8:
doInBackground
runs on a different Thread than the main UI, so you can't create a show a dialog here. Instead, override onPreExecute in your AsyncTask
, and do the test there.
回答9:
Internet connection also check either in onCreate()
or onResume()
method. There is no need to call inside the AsyncTask.
or You can call before call the AsyncTask execute() method
if(isOnline)
{
MyAsyncTask task=new MyAMyAsyncTask();
task.execute();
}
else
{
// no internet connection
}
来源:https://stackoverflow.com/questions/17880287/android-programmatically-check-internet-connection-and-display-dialog-if-notco