广播:(监听网络,开机状态)
2019-07-03 本文已影响0人
穿越平行宇宙
image.png
一、 需要添加的权限
<!-- 网络连接 -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<!-- 开机状态 -->
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
二、 静态添加开机状态的广播
<!-- 静态注册监听开机的广播 -->
<receiver
android:name=".type1.service.BootReminderReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
三、 activity 包下的
MainActivity.java
public class MainActivity extends AppCompatActivity {
private NetWorkChangeReceiver netWorkChangeReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 广播接收器
netWorkChangeReceiver = new NetWorkChangeReceiver();
// 意图过滤器:设置网络连接变化的活动
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
// 注册监听网络变化的广播
registerReceiver(netWorkChangeReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
// 注销广播
unregisterReceiver(netWorkChangeReceiver);
}
}
四、service 包下的
1. BootReminderReceiver.java:监听开机状态的广播接收器
public class BootReminderReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "开启成功", Toast.LENGTH_SHORT).show();
}
}
2. NetWorkChangeReceiver.java:动态注册监听网络状态的广播接收器
public class NetWorkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 获取网络管理器类
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
// 获取网络信息,需要网络连接权限
NetworkInfo activeNetworkInfo = null;
if (connectivityManager != null) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
}
// 根据 获取到的网络信息是否有,获取到的网络信息是否可用
if (activeNetworkInfo != null && activeNetworkInfo.isAvailable())
Toast.makeText(context, "有网", Toast.LENGTH_SHORT).show();
else
Toast.makeText(context, "没网", Toast.LENGTH_SHORT).show();
}
}