packagecom.example.broadcasttest2;importandroid.app.Activity;importandroid.content.BroadcastReceiver;importandroid.content.Context;importandroid.content.Intent;importandroid.content.IntentFilter;importandroid.net.ConnectivityManager;importandroid.net.NetworkInfo;importandroid.os.Bundle;importandroid.view.Menu;importandroid.view.MenuItem;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.Toast;public class MainActivity extendsActivity {privateIntentFilter intentFilter;privateLocalReceiver localReceiver;privateLocalBroadcastManager localBroadcastManager;privateNetworkChangeReceiver networkChangeReceiver;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intentFilter= newIntentFilter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver= newNetworkChangeReceiver();
registerReceiver(networkChangeReceiver,intentFilter);
localBroadcastManager= LocalBroadcastManager.getInstance(this);//获取实例
Button button=(Button) findViewById(R.id.button);
button.setOnClickListener(newOnClickListener() {
@Overridepublic voidonClick(View v) {//下面这行代码是用来全局广播的//Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");//下面这行代码是用来本地广播的(也就是app内部传递广播)
Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent);//发送本地广播//sendBroadcast(intent);//我们关闭上面一行代码,然后写另一种方法sendOrderedBroadcast,发送有序广播
sendOrderedBroadcast(intent,null);
}
});
intentFilter= newIntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROACAST");
localReceiver= newLocalReceiver();
localBroadcastManager.registerReceiver(localReceiver,intentFilter);//注册本地广播监听器
}
@Overrideprotected voidonDestroy() {super.onDestroy();//unregisterReceiver(networkChangeReceiver);
localBroadcastManager.unregisterRecerver(localReceiver);
}class NetworkChangeReceiver extendsBroadcastReceiver{
@Overridepublic voidonReceive(Context context,Intent intent) {
ConnectivityManager connectionMananger=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectionMananger.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();
}
}
}class LocalReceiver extendsBroadcastReceiver {
@Overridepublic voidonReceive(Context context,Intent intent) {
Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show();
}
}
}