笼统一点讲就是用来传输数据的。具体一点说就是:
1.实现了不同的程序之间的数据传输与共享,因为只要是和发送广播的action相同的接受者都能接受这个广播。
典型的应用就是android自带的短信,电话等等广播,只要我们实现了他们的action的广播,那么我们就能接收他们的数据了,
以便做出一些处理。比如说拦截系统短信,拦截骚扰电话等等
2.起到了一个通知的作用,比如在service中要通知主程序,更新主程序的UI等。因为service是没有界面的,
所以不能直接获得主程序中的控件,这样我们就只能在主程序中实现一个广播接受者专门用来接受service发过来的数据和通知了。
public class MainActivity extends Activity implements OnClickListener { |
14 |
15 | MyReceiver myReceiver; |
16 | IntentFilter intentFilter; |
17 | EditText etReceivedBroadcast; |
18 | Button btnSendBroadcast; |
19 | @Override |
20 | protected void onCreate(Bundle savedInstanceState) { |
21 | super .onCreate(savedInstanceState); |
22 | setContentView(R.layout.activity_main); |
23 | |
24 | etReceivedBroadcast = (EditText) findViewById(R.id.etReceivedBroadcast); |
25 | btnSendBroadcast = (Button) findViewById(R.id.btnSendBroadcast); |
26 | |
27 | //keep reference to Activity context |
28 | MyApplication myApplication = (MyApplication) this .getApplicationContext(); |
29 | myApplication.mainActivity = this ; |
30 |
31 | btnSendBroadcast.setOnClickListener( this ); |
32 | |
33 | myReceiver = new MyReceiver(); |
34 | intentFilter = new IntentFilter( "com.hmkcode.android.USER_ACTION" ); |
35 | } |
36 |
37 | @Override |
38 | protected void onResume() { |
39 | super .onResume(); |
40 | registerReceiver(myReceiver, intentFilter); |
41 |
42 | } |
43 | @Override |
44 | protected void onPause() { |
45 | super .onPause(); |
46 | unregisterReceiver(myReceiver); |
47 | } |
48 | |
49 | |
50 | @Override |
51 | public void onClick(View view) { |
52 | |
53 | Intent intnet = new Intent( "com.hmkcode.android.USER_ACTION" ); |
54 | sendBroadcast(intnet); |
55 | |
56 | } |
57 | |
58 | } |
public class MyReceiver extends BroadcastReceiver{ |
08 |
09 | @Override |
10 | public void onReceive(Context context, Intent intent) { |
11 | MainActivity mainActivity = ((MyApplication) context.getApplicationContext()).mainActivity; |
12 | mainActivity.etReceivedBroadcast.append( "broadcast: " +intent.getAction()+ "\n" ); |
13 | } |
14 | |
15 | } |