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?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答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">