Broadcast功能在于可以向手机中的其他程序发送消息,实现程序间互相通信。比如Android系统在启动,闹钟,来电等一些情况下,会广播一些消息给所有的接收者,其他程序在收到信息后可以做进一步动作。
今天的DEMO介绍一下,程序有两个Class。一个是主Activity,主要做界面显示,发送广播,另一个是广播接收器,用于收到主Activity广播后执行相应动作。
布局XML代码就不贴了,就一按钮。
main.java:
package com.pocketdigi.Broadcast;
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 main extends Activity {
/** Called when the activity is first created. */
static final String action1="Broadcast_action1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent it = new Intent(action1);
sendBroadcast(it);
//点击按钮后广播一个Intent,内容是action1
//action1这个字符串,相当于一个ID,接收广播识别用的
}
}
);
}
}
接收器Broadcastreceiver.java:
package com.pocketdigi.Broadcast;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class Broadcastreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//接收到后执行以下内容
//这里不用考虑接收到的是否就是我们要的广播
//因为这一步已经放在AndroidManifest.xml里设置了
Toast.makeText(context, "成功接收广播", Toast.LENGTH_LONG).show();
}
}
在AndroidManifest.xml里注册一下接收器:
<receiver android:name=".Broadcastreceiver">
<intent-filter>
<action android:name="Broadcast_action1" />
</intent-filter>
</receiver>
这段代码的意思是,如果广播的action是”Broadcast_action1″,就通知Broadcastreceiver这个接收器,代码放在application标签内
在代码中注册receiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if (MyLayout.ACTION_MOUSE_PRESSED.equals(intent.getAction())) {
mMouseImageView.setImageResource(R.drawable.image_first_0);
} else if (MyLayout.ACTION_MOUSE_RELEASED.equals(intent.getAction())) {
mMouseImageView.setImageResource(R.drawable.image_first_1);
}else if (MyLayout.ACTION_MOUSE_BAD.equals(intent.getAction())) {
//do nothing here
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.rcthird_layout);
init();
}
private void init() {
view = new MyLayout(this, null);
view.setBackgroundColor(R.color.third_background);
mButtonNextStep = (Button) this.findViewById(R.id.third_next_button);
mButtonNextStep.setOnClickListener(this);
mMouseImageView = (ImageView) this.findViewById(R.id.third_mouse);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(MyLayout.ACTION_MOUSE_PRESSED);
mIntentFilter.addAction(MyLayout.ACTION_MOUSE_RELEASED);
mIntentFilter.addAction(MyLayout.ACTION_MOUSE_BAD);
registerReceiver(receiver, mIntentFilter);
}