广播介绍:
(1)发送广播:
package hpu.java.wfy.activity;
import hpu.java.wfy.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
private Button btnSendBroadcast = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast);
btnSendBroadcast.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId() == R.id.btnSendBroadcast) {
//创建intent对象
Intent intent = new Intent();
intent.setAction(Intent.ACTION_EDIT);//设置action,该action要和AndroidManifest中的Action相同
intent.putExtra("param", "测试是否能够传递参数");//设置参数
//发送广播
this.sendBroadcast(intent);
}
}
}
(2)接收广播:
1.继承BroadcastReceiver
2.覆盖onRecerve方法
package hpu.java.wfy.broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class TestBroadcastReceiver extends BroadcastReceiver{
//构造方法
public TestBroadcastReceiver() {
System.out.println("TestBroadcastReceiver constructor!");
}
//重写onReceive()
public void onReceive(Context context, Intent intent) {
System.out.println("TestBroadcastReceiver onReceive()!");
//接收参数
String value = intent.getStringExtra("param");
System.out.println("value=" + value);
}
}
(3)注册广播:
<!-- action就是该接收器要接收的动作 -->
<!-- 注意:发送和接收的action要相同才能接收到 -->
<receiver android:name=".broadcast.TestBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.EDIT"/>
</intent-filter>
</receiver>
广播的生命周期:
运行结果:
11-30 10:28:51.663: I/System.out(307): TestBroadcastReceiver constructor!
11-30 10:28:51.673: I/System.out(307): TestBroadcastReceiver onReceive()!
11-30 10:28:51.673: I/System.out(307): value=测试是否能够传递参数
11-30 11:01:19.712: I/System.out(307): TestBroadcastReceiver constructor!
11-30 11:01:19.712: I/System.out(307): TestBroadcastReceiver onReceive()!
11-30 11:01:19.712: I/System.out(307): value=测试是否能够传递参数
1.由运行结果可以看出,每当发送一个广播,广播接收器就会创建一个对象,接着调用onRecerve()方法。
2.当前广播结束后就会销毁BroadcastReceiver对象。当再次发送广播的时候就会重新创建一个对象。