Android 的广播实现(Java);
Android的广播分为两类:
第一类:动态广播需要实现BroadcastReceiver接口;进行注册。
实例:
class guangbos extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null&&networkInfo.isAvailable()){
}else{
Toast.makeText(context,"无网络",Toast.LENGTH_SHORT).show();
}
}
}
上面代码就是继承了BroadcastReceiver,需要在这里面添加IntentFilter添加拦截器,系统发出了什么广播,可以拦截到。全部代码如下:
public class MainActivity extends AppCompatActivity {
private IntentFilter intentFilter;
public guangbos mguangbos;
private static final String TAG="TAG";
private boolean mCharge;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// intentFilter=new IntentFilter();
// intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");//connectivity_change
intentFilter=new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
mguangbos=new guangbos();
registerReceiver(mguangbos,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mguangbos);
}
class guangbos extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
if (networkInfo!=null&&networkInfo.isAvailable()){
}else{
Toast.makeText(context,"无网络",Toast.LENGTH_SHORT).show();
}
}
}
}
第二种是静态注册,也就是在Androidmanfest.xml中直接注册,
需要的材料:
1.一个实现了BroadcastReceiver的类
2.在Androidmanfest添加如下代码
<receiver android:name=".ico_Test"//测试类
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>