一、发送自定义广播
1.广播主要分为两种:
- 标准广播和有序广播
2.发送标准广播
- 先定义一个广播接收器来接收广播
package com.example.broadcasttest2; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class MyBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context,Intent intent) { Toast.makeText(context, "received in MyBroadcastReceiver", Toast.LENGTH_SHORT).show(); } }
- 上面的代码意义在于接收到自定义广播的时候,就会弹出"received in MyBroadcastReceiver"这句话,然后在AndroidManifest.xml中注册这个类
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > .......................................... <receiver android:name=".MyBroadcastReceiver"> <intent-filter> <action android:name="com.example.broadcasttest.MY_BROADCAST"/> </intent-filter> </receiver> </application>
- 上面的XML就是当定义的接收器接收到值
com.example.broadcasttest.MY_BROADCAST
的时候才会触发那个定义好的广播器 - 接下来我们可以猜到就是触发这条广播呗,我们用个按钮来触发这个广播吧
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" .......................................... android:id="@+id/button" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:text = "Send Broadcast" /> </LinearLayout>
package com.example.broadcasttest2; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class MainActivity extends Activity { private IntentFilter intentFilter; private NetworkChangeReceiver networkChangeReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button button = (Button) findViewById(R.id.button); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST"); sendBroadcast(intent); } }); } }
运行打包安装:
- 我们点击一下按钮
- 首先构建出了一个Intent对象,并把要发送的广播的值传入,然后调用了Context的sendBroadcast()方法将广播发送出去,这样所有监听com.example.broadcasttest.MY_BROADDCAST这条广播的广播接收器就会收到消息。此时发出去的广播就是一条标准广播。
二、源码:
- BroadcastTest2
- https://github.com/ruigege66/Android/tree/master/BroadcastTest2
- CSDN:https://blog.csdn.net/weixin_44630050
- 博客园:https://www.cnblogs.com/ruigege0000/
- 欢迎关注微信公众号:傅里叶变换,个人账号,仅用于技术交流,后台回复“礼包”获取Java大数据学习视频礼包