广播的作用:在系统内通知和判定执行状态。
广播的类型:分为标准广播和有序广播。
标准广播:是完全异步执行的广播,在广播发出后,广播接 收器会按随机顺序收到该条广播,并且时间差很短,可以认为是同时接收。
有序广播:是同步执行的广播,在广播发出后,只有一个广播接收器能接收该消息,当这个广播接收器执行完逻辑后,广播才会继续传递。
发送广播的步骤:
1 .首先定义一个广播接收器,用来接收广播,新建广播接收器继承自BroadcastReceiver,并且广播接收器要在AndroidManifest文件中注册,代码如下:
package com.example.text;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastRec extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "received ", Toast.LENGTH_LONG).show();
}
}
注册代码如下
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.text"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
</activity>
<activity
android:name=".Text"
android:label="炫酷的应用"><!--用于指定标题栏的内容,并且为启动器中应用程序显示的名称 -->
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastRec"><!-- 注册广播接收器 ,name指要该接收器的名字 -->
<intent-filter >
<action android:name="com.example.broadcast.Mybroadcast"/><!-- 这个name指能接收到的广播的名字 -->
</intent-filter>
</receiver>
</application>
</manifest>
2.在主界面中定义一个按钮,点击按钮发送广播,发送广播是要先构建Intent,并设置Intent的action,然后通过调用sendBroadcast()方法发送广播,代码如下:
package com.example.text;
import android.app.Activity;
import android.content.Intent;
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.TextView;
import android.widget.Toast;
public class Text extends Activity {
private TextView Tv;
private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
send =(Button) findViewById(R.id.button1);
send.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent("com.example.broadcast.Mybroadcast");//Intent对象中直接传入发送广播的值,
//即和注册文件中MyBroadcastRec能接收的广播的name一样,则MyBroadcastRec就可以接收该条广播了。
sendBroadcast(intent);
}
});
}
}
该代码写的是发送标准广播。