广播注册有两种方式:
一:常驻型注册(静态注册)在清单文件中注册,即使Activity关闭,也会收到广播
1. java代码
private ConnectionChangeReceiver mReceiver;
private Button btnSend;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// registerNetWorkReceiver();
initView();
}
public void initView(){
btnSend = (Button) findViewById(R.id.btnSend);
btnSend.setOnClickListener(this);
}
@Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setAction("android.net.conn");
// TODO 发送广播
sendBroadcast(intent);
}
2.清单文件:
<receiver android:name="com.example.MyNetWork.ConnectionChangeReceiver">
<intent-filter>
<action android:name="android.net.conn"></action>
</intent-filter>
</receiver>
3.加权限:
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
4.自定义挂广播
public class ConnectionChangeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager mManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mInfo = mManager.getActiveNetworkInfo();
if ( mInfo!= null && mInfo.isAvailable()){
if (mInfo.getType() == ConnectivityManager.TYPE_MOBILE){
Toast.makeText(context,"数据网络连接",Toast.LENGTH_SHORT).show();
}else if (mInfo.getType() == ConnectivityManager.TYPE_WIFI){
Toast.makeText(context,"无线网络连接",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(context,"没有网络连接",Toast.LENGTH_SHORT).show();
}
}
}
二:非常驻型注册(动态注册)清单文件中不需要注册,加权限就可以
1.java代码:
private ConnectionChangeReceiver mReceiver;
private Button btnSend;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerNetWorkReceiver();
}
/**
* 注册网络连接的广播
*/
private void registerNetWorkReceiver(){
// TODO 创建意图过滤器
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mReceiver = new ConnectionChangeReceiver();
registerReceiver(mReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mReceiver != null){
// TODO 取消注册
if (mReceiver != null){
unregisterReceiver(mReceiver);
}
}
}
2。自定义广播同上