其他分享
首页 > 其他分享> > android学习笔记(二) 动态注册广播例程

android学习笔记(二) 动态注册广播例程

作者:互联网

public class MainActivity extends AppCompatActivity {
    private NetworkStateChangeReceiver networkStateChangeReceiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IntentFilter intentFilter = new IntentFilter();//创建IntentFilter实例
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//添加action
        networkStateChangeReceiver = new NetworkStateChangeReceiver();//创建NetwokrStateChangeReceiver实例
        registerReceiver(networkStateChangeReceiver, intentFilter);//注册广播接收器
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkStateChangeReceiver);//动态注册的广播接收器需要取消注册
    }

    /**
     * 定义NetworkStateChangeReceiver类,继承自BroadcastReceiver
     */
    static class NetworkStateChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
        	//You need to call getSystemService on a Context!!!
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
                Toast.makeText(context, "networkInfo: is Available", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "networkInfo: not Available", Toast.LENGTH_SHORT).show();
            }
        }
    }
}

需要在AndriodManifest.xml注册权限

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

AndroidStudio会自动提示,点击Add会自动添加

标签:Toast,注册,例程,networkInfo,笔记,context,NetworkStateChangeReceiver,android,networkSta
来源: https://blog.csdn.net/weixin_44195460/article/details/117902015