I am creating an android app. I need to display a dialog when internet connection is not available.I don't need to write network connection check in every activity . how to implement this using services in android?
Asked
Active
Viewed 214 times
1
-
1Here's a link to the answer to that question: https://stackoverflow.com/a/22311205/1008011 – chornge Sep 27 '17 at 04:51
1 Answers
1
Create a class nameed CheckConnection
as bellow
Than you call this class where you want to check is INTERNET connection available or not
Code
public class ConnectionCheck {
public boolean isNetworkConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = cm.getActiveNetworkInfo();
if (ni == null) {
// There are no active networks.
return false;
} else
return true;
}
public AlertDialog.Builder showconnectiondialog(Context context) {
final AlertDialog.Builder builder = new AlertDialog.Builder(context)
.setIcon(R.mipmap.ic_launcher)
.setTitle("Error!")
.setCancelable(false)
.setMessage("No Internet Connection.")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
return builder;
}
}
Call above class where you want to check Internet connection: as above line
ConnectionCheck connectionCheck = new ConnectionCheck();
if (connectionCheck.isNetworkConnected(this)){// or your context pass here
//operation you want if connection available
}else {
connectionCheck.showconnectiondialog(this); //context pass here
}
And you must add Permission for accessing network state and Internet in to ManifestActivity.xml
:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE">

ND1010_
- 3,743
- 24
- 41
-
I don't need to add this code at every activity. I need to write the code once and check internet connection when changes suddenly. – Shrirambaabu Sep 27 '17 at 05:24
-
-
-
I don't want to call this function i every activity. i need a service when the internet is not available. – Shrirambaabu Sep 27 '17 at 05:58