一、新建项目
二、增加权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
三、代码
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);
}
//新建类继承 BroadcastReceiver 重写 onReceive
class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectionManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
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();
}
}
}
}
四、效果
扩展 一个解决方案中多个项目(类似VS Studio)
修改文件名称
一个多个app
点击完成即可
以上,瑞思拜