当使用服务在Android中无法使用互联网连接时如何显示对话框 [英] How to display dialog when internet connection not available in android using services
问题描述
我正在创建一个Android应用。当无法连接互联网时,我需要显示一个对话框。不需要在每个活动中都编写网络连接检查。
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?
推荐答案
创建一个名为 CheckConnection $ c $的类c>作为波纹管
Create a class nameed CheckConnection
as bellow
比起您要检查的此类,您是否要检查互联网连接是否可用
Than you call this class where you want to check is INTERNET connection available or not
代码
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
}
并且您必须添加访问网络状态和Internet的权限进入 ManifestActivity.xml
:
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">
这篇关于当使用服务在Android中无法使用互联网连接时如何显示对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!