android 广播接收者分析(2)

来源:互联网 发布:淘宝客快速打造爆款 编辑:程序博客网 时间:2024/06/08 17:50

ndroid系统会发送许多系统级别的广播,比如屏幕关闭,电池电量低等广播。同样应用可以发起自定义“由开发者定义的”广播。广播是从一个应用内部向另一个应用发送消息的途径之一。

BroadcastReceiver是一个可以监听和响应广播的组件。本文中,我们将会演示如何发送自定义广播以及如何通过编程和使用Manifest文件定义一个BroadcastReceiver来监听这一广播。

目标:

  • 如何发送广播
  • 如何创建一个broadcast receiver
  • 如何在Java代码中清单文件注册接收

环境与工具

  • Android Developer Tools (ADT) (or Eclipse + ADT plugin)
  • AVD Nexus S Android 4.3 “模拟器”
  • Min SDK 8
bigtiger02
bigtiger02
翻译于 6个月前

2人顶

 翻译的不错哦!

( 1 )创建布局UI

  • res/layout/activity_main.xml
01<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
02    xmlns:tools="http://schemas.android.com/tools"
03    android:layout_width="match_parent"
04    android:layout_height="match_parent"
05    android:paddingBottom="@dimen/activity_vertical_margin"
06    android:paddingLeft="@dimen/activity_horizontal_margin"
07    android:paddingRight="@dimen/activity_horizontal_margin"
08    android:paddingTop="@dimen/activity_vertical_margin"
09    android:orientation="vertical"
10    tools:context=".MainActivity" >
11 
12    <TextView
13        android:layout_width="wrap_content"
14        android:layout_height="wrap_content"
15        android:gravity="center_horizontal"
16        android:layout_gravity="center_horizontal"
17        android:text="Received Broadcasts" />
18    <Button
19        android:id="@+id/btnSendBroadcast"
20        android:layout_width="wrap_content"
21        android:layout_height="wrap_content"
22        android:gravity="center_horizontal"
23        android:layout_gravity="center_horizontal"
24        android:text="Send Broadcast"
25        />
26    <EditText
27        android:id="@+id/etReceivedBroadcast"
28        android:layout_width="match_parent"
29        android:layout_height="wrap_content"
30 
31        />
32 
33</LinearLayout>

( 2 ) 扩展 BroadcastReceiver

  • 创建一个叫做MyReceiver的对象,继承BroadcastReceiver.
  • 重写 onReceive() 方法,在EditText中打印intent的活动名称.
  • /src/com/hmkcode/android/MyReceiver.java
01package com.hmkcode.android;
02 
03import android.content.BroadcastReceiver;
04import android.content.Context;
05import android.content.Intent;
06 
07public 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}

( 3 ) 发送广播

  • 发送广播创建一个包含活动名称的Intent,将它传递给sendBroadcast()。
Intent i = new Intent("com.hmkcode.android.USER_ACTION");sendBroadcast(i);

( 4 ) 通过Java或XML方式注册BroadcastReceiver

你可以通过java代码动态注册或在Manifest xml文件中进行注册。

  • 使用Java代码

  • 创建BroadcastReceiver类的实例MyReceiverIntentFilter实例并将他们传递给registerReceiver()方法
@Override    protected void onResume() {        super.onResume();        registerReceiver(new MyReceiver(),          new IntentFilter("com.hmkcode.android.USER_ACTION"));    }
  • 在Manifest XML 文件中配置

  • 另外你可以在manifest文件中注册接收器
1<receiver android:name="com.hmkcode.android.MyReceiver" >
2    <intent-filter>
3        <action android:name="com.hmkcode.android.USER_ACTION" />
4    </intent-filter>
5</receiver>
bigtiger02
bigtiger02
翻译于 6个月前

1人顶

 翻译的不错哦!

( 5 ) Activity Class

  • /src/com/hmkcode/android/MainActivity.java
01package com.hmkcode.android;
02 
03import android.os.Bundle;
04import android.app.Activity;
05import android.content.Intent;
06import android.content.IntentFilter;
07import android.view.View;
08import android.view.View.OnClickListener;
09import android.widget.Button;
10import android.widget.EditText;
11 
12 
13public 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}

( 6 ) Manifest.XML

01<?xml version="1.0" encoding="utf-8"?>
02<manifest xmlns:android="http://schemas.android.com/apk/res/android"
03    package="com.hmkcode.android"
04    android:versionCode="1"
05    android:versionName="1.0" >
06 
07    <uses-sdk
08        android:minSdkVersion="8"
09        android:targetSdkVersion="17" />
10 
11    <application
12        android:name="com.hmkcode.android.MyApplication"
13        android:allowBackup="true"
14        android:icon="@drawable/ic_launcher"
15        android:label="@string/app_name"
16        android:theme="@style/AppTheme" >
17        <activity
18            android:name="com.hmkcode.android.MainActivity"
19            android:label="@string/app_name" >
20            <intent-filter>
21                <action android:name="android.intent.action.MAIN" />
22 
23                <category android:name="android.intent.category.LAUNCHER" />
24            </intent-filter>
25        </activity>
26         
27        <receiver android:name="com.hmkcode.android.MyReceiver" >
28            <intent-filter>
29                <action android:name="com.hmkcode.android.USER_ACTION" />
30            </intent-filter>
31        </receiver>
32         
33    </application>
34 
35</manifest>

注:如果你想通过Manifest XML文件注册接收器,那么需要从MainActivity类中移除onResumeonPause方法。

( 7 ) 获取Activity Context 的办法

当使用xml注册接收器时,系统将ReceiverResctrictredContext传递给onReceive()方法。为了能在EditText中进行打印,需要获取MainActivity context,因此需要通过扩展Application来持有MainActivity的引用。

view source
print?
01package com.hmkcode.android;
02 
03import android.app.Application;
04 
05public class MyApplication extends Application {
06 
07    @Override
08    public void onCreate() {
09        super.onCreate();
10    }
11     
12    MainActivity mainActivity;
13     
14}

注意:我们在Manifest文件中使用了MyApplication。

<application        android:name="com.hmkcode.android.MyApplication"
0 0
原创粉丝点击