动态注册广播 监听网络变化

观看书籍,还望指正

1, 创建intentFilter实例 并添加action android.net.conn.CONNECTIVITY_CHANGE

2, 定义一个新的内部类networkChangeReceiver继承BroadcasetReceiver 重写onReceiver()方法

3, newworkChangeReceiver实例 调用registerReceiver()注册

4,重载onDestroy()方法


代码如下:

优化前

MainActivity.java

import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter=new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver=new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); } @Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(networkChangeReceiver); } class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show(); } } }

优化后

MainActivity.java

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.v4.graphics.drawable.TintAwareDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); intentFilter=new IntentFilter(); intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE"); networkChangeReceiver=new NetworkChangeReceiver(); registerReceiver(networkChangeReceiver,intentFilter); } @Override protected void onDestroy(){ super.onDestroy(); unregisterReceiver(networkChangeReceiver); } class NetworkChangeReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent){ // Toast.makeText(context,"network changes",Toast.LENGTH_SHORT).show(); ConnectivityManager connectionManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE); //通过getSystemService()方法得到connectionManager的实例 NetworkInfo networkInfo=connectionManager.getActiveNetworkInfo(); //通过getActiveNetworkInfo()方法得到networkInfo的实例 if(networkInfo!=null &&networkInfo.isAvailable()){ Toast.makeText(context,"network is available",Toast.LENGTH_SHORT).show(); }else { Toast.makeText(context,"network is unavailable",Toast.LENGTH_SHORT).show(); } } } }


你可能感兴趣的:(动态注册广播 监听网络变化)