Android发送和接收自定义Broadcast
BroadcastReceiver意为广播接收,通过它可以实现进程间通信也可以实现进程内部进行通信,对于广播的消息我们只处理感兴趣的消息,可以接收系统的广播(短信、开机)也可以接收自定义的广播,但都需要注册才能接收,注册的方式又分两种,一是在AndroidMainfest.xml中注册,二是在代码中注册。
BroadcastReceiver是一个抽象的类,我们需要继承它才能创建对象
创建一个类ReceiveMsg.java继承BroadcastReceiver,并定义两个自定义的消息
package com.example.broadcastdemo;import com.example.receivermsg.ReceiverMsg;import android.app.Activity;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;import android.view.Menu;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class MainActivity extends Activity implements OnClickListener {private Button sendMsg = null;private Button sendReg = null;private ReceiverMsg receiver = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);sendMsg = (Button) findViewById(R.id.sendMsg);sendReg = (Button) findViewById(R.id.sendRegMsg);sendMsg.setOnClickListener(this);sendReg.setOnClickListener(this);// 生成一个BroiadcastReceiver对象receiver = new ReceiverMsg();// 生成一个IntentFilter对象IntentFilter filter = new IntentFilter();// 为IntentFilter添加一个Actionfilter.addAction(ReceiverMsg.MSG);// 将BroadcastReceiver对象注册到系统当中registerReceiver(receiver, filter);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this adds items to the action bar if it is present.getMenuInflater().inflate(R.menu.main, menu);return true;}/** * 按钮监听 */@Overridepublic void onClick(View arg0) {// TODO Auto-generated method stubint id = arg0.getId(); // 用来区分点击的是哪个按钮if (id == R.id.sendMsg) {Intent intent = new Intent();intent.setAction(ReceiverMsg.MSG);sendBroadcast(intent);System.out.println("send own msg");} else if (id == R.id.sendRegMsg) {Intent intent = new Intent();intent.setAction(ReceiverMsg.REG_MSG);sendBroadcast(intent);System.out.println("send reg msg");}}}在onReceive中接收到感兴趣的消息就可以根据需要进行处理,比如更新播放进度、更新时间等操作。点击打开链接