广播是一种信息的发送机制,就像电视那样,用户可以选择自己喜欢的电视节目,电视台(发送方)不会考虑用户是如何对电视信息进行处理的,不管用户是否在收看此频道,点尸体爱都要发送电视信号。
在Android中存在着各种各样的广播信息,如手机刚启动时的提示信息、电池不足的警告信息和来点信息等,都会通过广播形式发送给用户,而处理的形式由用户自己决定。
在Android中开发者可以定义自己的广播组件,但是所用的广播组件都是一个类的形式出现,而且该类必须继承自BroadcastReceive类,而且还需向Android系统注册。
系统中定义了很多的广播组件,分别代表不同的功能。然而有时候开发者需要自己定义广播组件用到特定的APP中,下面例程介绍自定义广播组件的方法。
布局文件activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="广播" />
</LinearLayout>
<span style="color: rgb(255, 0, 0); font-size: 18px; "><strong>Java文件MainActivity.java</strong></span>
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
MyReceiver myr = new MyReceiver();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button myButton = (Button) this.findViewById(R.id.button1);
myButton.setOnClickListener(
new OnClickListener(){
@Override
public void onClick(View v) {
Intent it = new Intent("LIZHAOJING");//自定义广播
it.putExtra("msg","lizhaojing");//放入自定义信息
MainActivity.this.sendBroadcast(it);//发送广播
IntentFilter filter = new IntentFilter("LIZHAOJING");//接收广播过滤器
MainActivity.this.registerReceiver(myr,filter);//注册广播
}
}
);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unregisterReceiver(myr);//注销广播
super.onDestroy();
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyReceiver extends BroadcastReceiver{//继承自BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {//重写的onReceive方法
if("LIZHAOJING".equals(intent.getAction())){
String msg = intent.getStringExtra("msg");
Toast.makeText(context, "广播启动"+msg, Toast.LENGTH_LONG).show();
}
}
}