一提到广播我们第一感觉就会联想到小时候村里面的广播,安卓的广播机制也是类似于大喇叭。有发送广播的地方,也有接收广播的地方。但是具体怎么操作呢,我们来一步一步的看下去~
1.创建好Intent发送对象,构造方法如下
java //参数是需要发送的信息,一般是字符串 public static final String ACTION_INTENT_TEST = "com.tao.broadCastReceive"; Intent intent = new Intent(ACTION_INTENT_TEST);
2.使用Activity中的一个方法进行发送广播
//此方法是Context中的方法,同步广播sendBroadcast(intent);
sendOrderedBroadcast(intent,null);
public class Receiver extends BroadcastReceiver{ public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); ... } }
<receiver android:name=".Receiver"> <intent-filter android:priority="1000"> <action android:name="com.tao.broadCastReceive"/> </intent-filter> </receiver>
这样就完成一个广播的发送了,当然如果需要接收系统的广播,则可以在AndroidMainFest文件中进行设置Action属性,则就可以接收系统发出的广播信息。
public class MainActivity extends AppCompatActivity { private Button sendBroadCastReceive; private EditText titleContent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendBroadCastReceive= (Button) findViewById(R.id.sendBroadCastReceive); titleContent= (EditText) findViewById(R.id.titleContent); sendBroadCastReceive.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent sendBroadCast=new Intent(); sendBroadCast.setAction("coom.tao.selfBroadCastReceive"); sendBroadCast.putExtra("title",titleContent.getText().toString().trim()); sendBroadcast(sendBroadCast); } }); }}
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.tao.boedercast.MainActivity"> <EditText android:id="@+id/titleContent" android:layout_width="match_parent" android:layout_height="40dp" android:layout_marginRight="20dp" android:layout_marginLeft="20dp" android:layout_marginBottom="10dp" android:layout_above="@+id/sendBroadCastReceive" android:hint="请输入发送的内容" /> <Button android:id="@+id/sendBroadCastReceive" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerInParent="true" android:text="发送广播" /></RelativeLayout>
预览
public class MyBroadCastReceive extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String titleContent=intent.getStringExtra("title"); Toast.makeText(context,titleContent,Toast.LENGTH_LONG).show(); }}
<receiver android:name=".MyBroadCastReceive"> <intent-filter android:priority="1000"> <action android:name="coom.tao.selfBroadCastReceive"></action> </intent-filter> </receiver>
一个简单的自定义广播完成了,欢迎大家指正批评,谢谢!
本博客内容一致同步到本人的简书博客:http://www.jianshu.com/p/c01397361ba0 欢迎访问留言交流