安卓广播接受器——创建网络连接状态的程序

介绍广播接收器
在这里我们先介绍一下广播接收器。广播(Broadcast)是一种广泛应用在应用程序之间传输信息的机制可以通知多个对象的事件通知机制,而BroadcastReceiver(广播接收器)则是用于接受系统和应用的广播并对其进行响应的组件。
广播接收器可以字有地对自己感兴趣的广播进行注册,这样当有相应的广播发出时,广播接收器就能接收到该广播,并在内部处理相应的逻辑。
注册广播的方式一般有两种,在代码中注册和在AndroidManifest.xml中注册,其中前者也被称为动态注册,后者被称为静态注册。在我之前我已经讲过静态注册。现在我要写的是动态注册。
话不多说,直接上案例:
当点击登录按钮时会出来下图所示:在这里插入图片描述
当没有网的时候会出来下图所示:
在这里插入图片描述
这就是我创建的一个简单的案例。
先创建一个项目:
在xml中编写:


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:id="@+id/net"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_marginTop="0dp"
        android:background="@color/warn1"
        android:orientation="horizontal"
        android:visibility="invisible"
        >
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="22dp"
            android:layout_height="22dp"
            android:layout_marginTop="9dp"
            android:layout_marginLeft="20dp"
            android:src="@drawable/warn"
            />
        <TextView
            android:id="@+id/textView1"
            android:layout_width="wrap_content"
            android:layout_height="24dp"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="20dp"
            android:text="当前网络连接不可用!"
            />
    </LinearLayout>
    <EditText
        android:layout_marginTop="200dp"
        android:id="@+id/userId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入账号"
        />
    <EditText
        android:id="@+id/userPw"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="请输入密码"
        android:inputType="textPassword"
        />
    <Button
        android:id="@+id/login_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="登录"
        android:layout_marginTop="50dp"
        />

</LinearLayout>

在Java中编写:


public class MainActivity extends AppCompatActivity {
  private NetworkChangeReceiver networkChangeReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button=(Button)findViewById(R.id.login_btn);
        final LinearLayout net=(LinearLayout)findViewById(R.id.net);
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        NetworkChangeReceiver networkChangeReceiver=new NetworkChangeReceiver();
        registerReceiver(networkChangeReceiver,intentFilter);


    }
    class NetworkChangeReceiver extends BroadcastReceiver{


        @Override
        public void onReceive(Context context, Intent intent) {
            //ConnectivityManager主要管理和网络连接相关的操作
            //getSystemService获取系统的连接服务
            ConnectivityManager connectivityManager= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // NetworkInfo类包含了对wifi和mobile两种网络模式连接的详细描述
            // 下面表示获取代表联网状态的NetWorkInfo对象
            //getActiveNetworkInfo()获取网络的连接情况
            NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
            if (networkInfo!=null && networkInfo.isAvailable()){
                Toast.makeText(context,"网络已连接",Toast.LENGTH_SHORT).show();
            }else {
                Toast.makeText(context,"网络连接失败",Toast.LENGTH_SHORT).show();
                @SuppressLint("WrongViewCast") Button button=(Button)findViewById(R.id.login_btn);
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        LinearLayout  net=(LinearLayout)findViewById(R.id.net) ;
                        net.setVisibility(View.VISIBLE);
                    }
                });
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkChangeReceiver);
    }
}

我们观察onCreate()方法,首先我们创建了一个IntentFilter的实例,并给它添加了一个值为android.conn.CONNECTIVITY_CHANGE的action,为什么要添加这个值呢?因为当网络状态发生改变时,系统发出的正是一条值为android.conn.CONNECTIVITY_CHANGE的广播,也就是说我们的广播接收器想要监听什么广播,就在这里添加相应的action。接下来创建一个NetworkChangeReceiver的实例,然后调用registerReceiver()方法进行注册,将NetworkChangeReceiver的实例和IntentFilter的实例都传进去,这样
NetworkChangeReceiver就会收到所有值为android.conn.CONNECTIVITY_CHANGE的广播,也就是实现了监听网络变化的功能。
最后要记得,动态注册给广播接收器一定都要取消注册才行,这里我们是在onDestroy()方法中通过调用unregisterReceiver()方法来实现取消注册的。
在onReceive()方法中,我们首先通过个体System Service()方法得到了ConnectivityManager的实例,这是一个系统服务类,专门用于管理网络连接的,然后调用它的getActiveNetworkInfo()方法可以得到NetworkInfo的实例,接着调用NetworkInfo的isAvailable()方法就可以判断出当前是否有网络了。
在这里插入图片描述
在这里编写


<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

这样就成功了,就简单的创建了一个动测注册一个广播接收器来查看网络状态的案例。
最后在送给大家一个礼物(截图大佬的):
在这里插入图片描述

发布了5 篇原创文章 · 获赞 6 · 访问量 151

猜你喜欢

转载自blog.csdn.net/jzdcuccess/article/details/105458788