Android学习总结——判断网络状态
package com.example.xch.broadcasttest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button getNetworkState;
private IntentFilter intentFilter;
private NetworkChangeReceiver networkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getNetworkState=(Button)findViewById(R.id.get_network_state);
getNetworkState.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.get_network_state:
intentFilter=new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//网络状态发生改变时发出这一条广播
networkChangeReceiver=new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(networkChangeReceiver);//关闭广播
}
class NetworkChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//getSystemService()方法得到ConnectivityManager实例,这是一个系统服务类,用于管理网络连接
ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
//getActiveNetworkInfo()方法得到NetworkInfo实例
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
//调用NetworkInfo的isAvailable()方法判断当前是否有网络
if(networkInfo!=null&&networkInfo.isAvailable()){
Toast.makeText(context,"网络可用",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"网络不可用",Toast.LENGTH_SHORT).show();
}
}
}
}
记得声明权限,否则程序会崩溃。
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>