android网络状态检测
Ⅰ android 怎么监控网络状态可以访问互联网而不是连接状态
在开发android应用时,涉及到要进行网络访问,时常需要进行网络状态的检查,以提供给用户必要的提醒。一般可以通过ConnectivityManager来完成该工作。
ConnectivityManager有四个主要任务:
1、监听手机网络状态(包括GPRS,WIFI, UMTS等)
2、手机状态发生改变时,发送广播
3、当一个网络连接失败时进行故障切换
4、为应用程序提供可以获取可用网络的高精度和粗糙的状态
当我们要在程序中监听网络状态时,只要一下几个步骤即可:
1、定义一个Receiver重载其中的onReceive函数,在其中完成所需要的功能,如根据WIFI和GPRS是否断开来改变空间的外观
复制代码 代码如下:
connectionReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mobNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifiNetInfo = connectMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (!mobNetInfo.isConnected() && !wifiNetInfo.isConnected()) {
Log.i(TAG, "unconnect");
// unconnect network
}else {
// connect network
}
}
};
2、在适当的地方注册Receiver,可以在程序中注册,在onCreate中调用如下函数即可:
复制代码 代码如下:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(connectionReceiver, intentFilter);
3、在适当时取消注册Receiver,可以在程序中取消,在onDestroye中调用如下函数即可:
复制代码 代码如下:
if (connectionReceiver != null) {
unregisterReceiver(connectionReceiver);
}
Ⅱ android 判断是否有网络
用户手机当前网络可用:WIFI、2G/3G网络,用户打开与不打开网络,和是否可以用是两码事。可以使用指的是:用户打开网络了并且可以连上互联网进行上网。
检测当前网络是否可用,代码如下:
/**
* 检测当的网络(WLAN、3G/2G)状态
* @param context Context
* @return true 表示网络可用
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
/**
* 检测当的网络(WLAN、3G/2G)状态
* @param context Context
* @return true 表示网络可用
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null && info.isConnected())
{
// 当前网络是连接的
if (info.getState() == NetworkInfo.State.CONNECTED)
{
// 当前所连接的网络可用
return true;
}
}
}
return false;
}
在AndroidManifest.xml文件添加的权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
Ⅲ Android检测是否有网络的代码
public class CheckNetwork {
private NetworkStateReceiver netStateReceiver;
private Context mContext;
private long servicetimes = 0;
private Utility myUtility = null;
private int runInternerTime = 0;
private HandlerNetwork mHandlerNetwork = new HandlerNetwork();
private static CheckNetwork mNetworkState = null;
private Map<String, Handler> mHandlerOuterMap = new HashMap<String, Handler>();
public static CheckNetwork getNetworkState(Context context) {
if (mNetworkState == null) {
mNetworkState = new CheckNetwork(context);
}
return mNetworkState;
}
private CheckNetwork(Context context) {
mContext = context;
myUtility = new Utility(mContext);
registNetworkStatusReceiver();
}
public void registNetworkStatusReceiver() {
netStateReceiver = new NetworkStateReceiver(mHandlerNetwork);
IntentFilter filter = new IntentFilter(
"android.net.conn.CONNECTIVITY_CHANGE");
filter.addAction("android.intent.action.MY_NET_BOOTCHECK");
mContext.registerReceiver(netStateReceiver, filter);
Intent intent = new Intent("android.intent.action.MY_NET_BOOTCHECK");
mContext.sendBroadcast(intent);
}
/**
* 增加一个网络状态消息接受者
*
* @param key
* @param handler
*/
public void addHandler(String key, Handler handler) {
mHandlerOuterMap.put(key, handler);
if (!key.equals("IntegrateActHandlerKey")) {
// 当整合页添加handle时,网络状态还没准备好,所以不通过handle对外发通知
sendNetworkMessage(mHandlerOuterMap);
}
}
/**
* 向接受者集合中的接受者发送网络状态的消息
*
* @param map
*/
public static void sendNetworkMessage(Map<String, Handler> map) {
Set<String> key = map.keySet();
for (Object element : key) {
String s = (String) element;
Message msg = Message.obtain();
msg.what = GlobalParams.Handle_Msg.NetWorkStatus.ordinal();
map.get(s).sendMessage(msg);
}
}
private class HandlerNetwork extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg.what == GlobalParams.Handle_Msg.ConnectSuccess.ordinal()) {
if (System.currentTimeMillis() - servicetimes > 3000) {// 防止短时间内接收多个广播,执行多次
runInternerTime = 0;
servicetimes = System.currentTimeMillis();
new CheckServerThread().start();
}
} else if (msg.what == GlobalParams.Handle_Msg.ConnectFail
.ordinal()) {
if (System.currentTimeMillis() - servicetimes > 2000) {// 防止短时间内接收多个广播,执行多次
servicetimes = System.currentTimeMillis();
runInternerTime++;
if (runInternerTime > 3) {
// Intent intent = new Intent(context,
// IntegrateActivity.class);
// context.startActivity(intent);
GlobalParams.NetworkStatus = 0;
sendNetworkMessage(mHandlerOuterMap);
} else {
Log.e("RUN", "本地连接不上尝试第" + runInternerTime + "次");
Message msgrun = Message.obtain();
msgrun.what = GlobalParams.Handle_Msg.InternerFail
.ordinal();
mHandlerNetwork.sendMessageDelayed(msgrun, 3000);
}
}
} else if (msg.what == GlobalParams.Handle_Msg.InternerFail
.ordinal()) {
//检测棒子与路由器间的连接不足3次时,继续检测
Intent intent = new Intent(
"android.intent.action.MY_NET_BOOTCHECK");
mContext.sendBroadcast(intent);
}else if(msg.what==GlobalParams.Handle_Msg.NetWorkStatusIn.ordinal()){
if(msg.arg1==0){
GlobalParams.NetworkStatus = 2;
sendNetworkMessage(mHandlerOuterMap);
}else{
GlobalParams.NetworkStatus = 1;
sendNetworkMessage(mHandlerOuterMap);
}
}
}
}
private class CheckServerThread extends Thread{
@Override
public void run() {
File f = new File(Environment.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher/Images");
if (!f.exists())
f.mkdirs();
File ftemp = new File(Environment.getExternalStorageDirectory()
.getPath() + "/CudgelLauncher/Temp");
if (!ftemp.exists())
ftemp.mkdirs();
// 等待SD卡准备完成
while (true) {
try {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
// 因为旧的配置文件都不适合用于新版,所以要把旧的都清除再重新加载
myUtility.delete(new File("/data/data/"
+ GlobalParams.PROCESSPACKNAME
+ "/databases/cudgellauncher"));
myUtility.delete(new File("/system/media/cudgel"));
myUtility.delete(new File("/mnt/sdcard/CudgelLauncher"));
break;
}
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
XmlParser parser = new XmlParser();
File fileConfig = new File("/mnt/sdcard/CudgelLauncher/config.xml");
File file = new File("/mnt/sdcard/CudgelLauncher/ConfigInterface.xml");
while (true) {
try {
Map<String, String> mapConfig = parser
.getServiceAsmx(fileConfig);
Map<String, String> mapInterface = parser.getServiceAsmx(file);
if (!fileConfig.exists() || mapConfig == null
|| !mapConfig.containsKey("area") || !file.exists()
|| mapInterface == null
|| !mapInterface.containsKey("servicenamespace")) {
// 第一次运运没配置文件时或防止配置文件被损坏,重新复制
myUtility.saveConfigFile(Environment
.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher", "Config.xml", R.raw.config,
mContext);
myUtility.saveConfigFile(Environment
.getExternalStorageDirectory().getPath()
+ "/CudgelLauncher", "ConfigInterface.xml",
R.raw.configinterface, mContext);
} else {
GlobalParams.AreaID = mapConfig.get("area");
break;
}
} catch (Exception e) {
e.printStackTrace();
}
}
//开始检测通不通公网
PingAddrUtils pingAddrUtils=new PingAddrUtils(mHandlerNetwork,GlobalParams.Handle_Msg.NetWorkStatusIn.ordinal());
pingAddrUtils.startPingAddr();
super.run();
}
}
}
ublic class PingAddrUtils {
private final static byte[] writeLock = new byte[0];
private String[] urls = new String[] { "tiipot.chinadhia.com",
"www.youku.com", "v.qq.com", "www.letv.com", "www..com",
"www.pptv.com", "tv.sohu.com" };
private String[] names = new String[] { "云联", "优酷", "腾讯", "乐视", "网络",
"pptv", "搜狐" };
private boolean[] isConected = { false, false, false, false, false, false,
false };
private Handler mHandler;
private int msgWhat;
private Timer timer;
/**
* mHandler用于接收返回成功连接或失败的消息
*
* @param mHandler
* @param mContext
*/
public PingAddrUtils(Handler mHandler, int msgWhat) {
this.mHandler = mHandler;
this.msgWhat = msgWhat;
}
/**
* 开始ping地址,返回值通过消息形式发送到构造方法传入的Handler,msg.What也是用构造方法传入的msgWhat
* 参数说明arg1:0失败;1通了;obj:用于生成二维码的字符串(String)
*
* @param msgWhat
*/
public void startPingAddr() {
// 开始检测时把状态都置为false以防重复检测时出现错误结果
for (int i = 0; i < isConected.length; i++) {
isConected[i] = false;
}
for (int i = 0; i < urls.length; i++) {
new IpAddrThread(i).start();
}
timer = new Timer();
timer.schele(new TimerTask() {
@Override
public void run() {
if (!isAllConected()) {// 全通线程中已处理了,所以这里只考虑没有全通的情况
boolean isAnyOneConected = false;
for (int i = 0; i < isConected.length; i++) {
isAnyOneConected = isAnyOneConected || isConected[i];
}
if (isAnyOneConected) {
sendMessage(1);// 有某个地址连接成功了。
} else {
sendMessage(0);// 全部地址连接失败。
}
}
}
}, 9000);// 9秒后
}
/***
* 判断是否所有地址都一ping通
*
* @return
*/
private boolean isAllConected() {
boolean isAllConected = true;
for (int j = 0; j < isConected.length; j++) {
// 所有都为TRUE isAllConected才为TRUE
isAllConected = isAllConected && isConected[j];
}
return isAllConected;
}
class IpAddrThread extends Thread {
int IpNum;
public IpAddrThread(int IpNum) {
this.IpNum = IpNum;
}
@Override
public void run() {
try {
Process p = Runtime.getRuntime().exec(
"ping -c 3 -w 5 " + urls[IpNum]);
int status = p.waitFor();
if (status == 0) {
// pass
// mPingIpAddrResult = "连接正常";
setThisIpTrue(IpNum);
} else {
// Fail:Host unreachable
// mPingIpAddrResult = "连接不可达到";
}
} catch (UnknownHostException e) {
// Fail: Unknown Host
// mPingIpAddrResult = "出现未知连接";
} catch (IOException e) {
// Fail: IOException
// mPingIpAddrResult = "连接出现IO异常";
} catch (InterruptedException e) {
// Fail: InterruptedException
// mPingIpAddrResult = "连接出现中断异常";
}
}
}
/**
* 生成用于产生二维码的字符串。01~10~21~31~41~50~61,有7组结果,用符号~分隔,每组结果都有两位数字,第一位数字代表是哪个服务器(
* 0是XX,1是优酷,2是 腾讯, 3是乐视, 4是网络,5是pptv,6是搜狐),第二位数字代码ping的结果(0表示不通,1表示已通)
*
* @return
*/
private String getQRCodeString() {
String oRCodeString = "";
for (int i = 0; i < isConected.length; i++) {
int state = 0;
if (isConected[i]) {
state = 1;
}
oRCodeString = oRCodeString + i + state;
if (i < isConected.length - 1) {
oRCodeString = oRCodeString + "~";
}
}
writeFileSdcard(oRCodeString);
return oRCodeString;
}
/**
* 写入SD卡
*
* @param filePath
* @param message
*/
private void writeFileSdcard(String message) {
try {
File file = new File("/mnt/sdcard/netstatus.txt");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
// FileOutputStream fout = openFileOutput(fileName, MODE_PRIVATE);
FileOutputStream fout = new FileOutputStream(file);
byte[] bytes = message.getBytes();
fout.write(bytes);
fout.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 定义消息并发送
*
* @param state
*/
private void sendMessage(int state) {
Message msg = Message.obtain();
msg.what = msgWhat;
msg.arg1 = state;// 全通
msg.obj = getQRCodeString();
mHandler.sendMessage(msg);
}
/**
* 把该ipNum代表的地址的通达状况置为True并判断是否所有都已联通,如果都已连通则发送成功连接的消息
*
* @param IpNum
*/
private void setThisIpTrue(int IpNum) {
synchronized (writeLock) {
isConected[IpNum] = true;// 把本地址的标记置为true;
if (isAllConected()) {
sendMessage(1);
timer.cancel();
timer = null;
}
}
}
}
Ⅳ android 怎么判断网络状态
获取android系统的连接服务可判断网络连接状态,代码如下
public class NetUtils{
public static boolean isNetworkConnected(Context context){
ConnectivityManager mConnectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] infos = cm.getAllNetworkInfo();
for(NetworkInfo info:infos){
if(info.isAvailable()&&info.isConnected()){
return true;
}
}
return false;
}
}
NetworkInfo的isAvailable()和isConnected()有以下5种状态:
在WLAN设置界面
1,显示连接已保存,但标题栏没有,即没有实质连接上:isConnected()==false,isAvailable()=true
2,显示连接已保存,标题栏也有已连接上的图标:isConnected()==true,isAvailable()=true
3,选择不保存后:isConnected()==false,isAvailable()=true
4,选择连接,在正在获取IP地址时:isConnected()==false,isAvailable()=false
5,连接上后:isConnected()==true,isAvailable()=true
Ⅳ Android系列之如何判断网络链接状态
获取android系统的连接服务可判断网络连接状态,代码如下
java">publicclassNetUtils{
(Contextcontext){
=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[]infos=cm.getAllNetworkInfo();
for(NetworkInfoinfo:infos){
if(info.isAvailable()&&info.isConnected()){
returntrue;
}
}
returnfalse;
}
}
NetworkInfo的isAvailable()和isConnected()有以下5种状态:
在WLAN设置界面
1,显示连接已保存,但标题栏没有,即没有实质连接上:isConnected()==false,isAvailable()=true
2,显示连接已保存,标题栏也有已连接上的图标:isConnected()==true,isAvailable()=true
3,选择不保存后:isConnected()==false,isAvailable()=true
4,选择连接,在正在获取IP地址时:isConnected()==false,isAvailable()=false
5,连接上后:isConnected()==true,isAvailable()=true
Ⅵ 如何判断 android 网络状态
在屏幕的上方有没有E\G\H\3G的图标,图标下方是打对勾的还是上下箭头?如果有就代表你的网络是开启的
Ⅶ android 怎么判断当前网络连接是否可以连接到外网
Android里判断是否可以上网,常用的是如下方法:
/**
* 检测网络是否连接
*
* @return
*/
private boolean isNetworkAvailable() {
// 得到网络连接信息
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
// 去进行判断网络是否连接
if (manager.getActiveNetworkInfo() != null) {
return manager.getActiveNetworkInfo().isAvailable();
}
return false;
}
有时候我们连接上一个没有外网连接的WiFi或者有线就会出现这种极端的情况,目前Android SDK还不能识别这种情况,一般的解决办法就是ping一个外网。
/* @author suncat
* @category 判断是否有外网连接(普通方法不能判断外网的网络是否连接,比如连接上局域网)
* @return
*/
public static final boolean ping() {
String result = null;
try {
String ip = "www..com";// ping 的地址,可以换成任何一种可靠的外网
Process p = Runtime.getRuntime().exec("ping -c 3 -w 100 " + ip);// ping网址3次
// 读取ping的内容,可以不加
InputStream input = p.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(input));
StringBuffer stringBuffer = new StringBuffer();
String content = "";
while ((content = in.readLine()) != null) {
stringBuffer.append(content);
}
Log.d("------ping-----", "result content : " + stringBuffer.toString());
// ping的状态
int status = p.waitFor();
if (status == 0) {
result = "success";
return true;
} else {
result = "failed";
}
} catch (IOException e) {
result = "IOException";
} catch (InterruptedException e) {
result = "InterruptedException";
} finally {
Log.d("----result---", "result = " + result);
}
return false;
}
Ⅷ android判断移动网络是否打开
Android 判断网络状态这一应用技巧在实际应中是比较重要的。那么,在Android操作系统中,如何能够正确的判断我们所连接的网络是否断开:
public class ConnectionChangeReceiver extends
BroadcastReceiver
{
@Override
public void onReceive( Context context, Intent intent )
{
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService
( Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.
getActiveNetworkInfo();
NetworkInfo mobNetInfo = connectivityManager.getNetworkInfo
( ConnectivityManager.TYPE_MOBILE );
if ( activeNetInfo != null )
{
Toast.makeText( context, "Active Network Type : " +
activeNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
if( mobNetInfo != null )
{
Toast.makeText( context, "Mobile Network Type : " +
mobNetInfo.getTypeName(), Toast.LENGTH_SHORT ).show();
}
}
}
< !-- Needed to check when the network connection changes -->
< uses-permission android:name="android.permission.
ACCESS_NETWORK_STATE"/>
< receiver android:name="com.blackboard.androidtest.
receiver.ConnectionChangeReceiver"
android:label="NetworkConnection">
< intent-filter>
< action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
< /intent-filter>
< /receiver>
Ⅸ androidstudio中实现显示手机当前网络状态
1、首先先用usb线连接android手机,然后输入指令:adbtcpip,端口号默认为5555。
2、设置端口号后,然后查看设置中手机的ip地址。
3、通过adb连接ip地址adbconnectip地址。
4、打开androidstudio,可以看到手机已经连接上了。
Ⅹ android 如何判断网络是否能够上网
实现步骤:
下面解决办法来自于android学习手册,android学习手册包含9个章节,108个例子,源码文档随便看,例子都是可交互,可运行,源码采用android studio目录结构,高亮显示代码,文档都采用文档结构图显示,可以快速定位。360手机助手中下载。排到第三个。
1、获取ConnectivityManager对象
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
2、获取NetworkInfo对象
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
3、判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
4、在AndroidManifest.xml中添加访问当前网络状态权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
代码如下:
public class ClassTestDemoActivity extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isNetworkAvailable(ClassTestDemoActivity.this))
{
Toast.makeText(getApplicationContext(), "当前有可用网络!", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "当前没有可用网络!", Toast.LENGTH_LONG).show();
}
}
/**
* 检查当前网络是否可用
*
* @param context
* @return
*/
public boolean isNetworkAvailable(Activity activity)
{
Context context = activity.getApplicationContext();
// 获取手机所有连接管理对象(包括对wi-fi,net等连接的管理)
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager == null)
{
return false;
}
else
{
// 获取NetworkInfo对象
NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();
if (networkInfo != null && networkInfo.length > 0)
{
for (int i = 0; i < networkInfo.length; i++)
{
System.out.println(i + "===状态===" + networkInfo[i].getState());
System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
// 判断当前网络状态是否为连接状态
if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
}
}
return false;
}
}