广播是Android四大组件之一,在我们的应用开发中也占据着重要的地位,我们在很多时候和很多场景中都需要使用到广播,那么接下来我们就说一下广播接收者的两种注册方式:
第一种:在androidmanifest.xml中注册。
在配置文件中注册的接收者的特点是即使应用程序已被关闭,该接收者依然可接受它感兴趣的广播,比如手机电池电量的广播接收者,没有必要将某个程序开启。
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16 |
<
application
android:
icon
=
"@drawable/icon"
android:
label
=
"@string/app_name"
>
<
activity
android:
name
=
".MainActivity"
android:
label
=
"@string/app_name"
>
<
intent
-
filter
>
<
action
android:
name
=
"android.intent.action.MAIN"
/>
<
category
android:
name
=
"android.intent.category.LAUNCHER"
/>
</
intent
-
filter
>
</
activity
>
<!--
广播接收者
1
-->
<
receiver
android:
name
=
".BroadcastReceiver1"
>
<
intent
-
filter
>
<
action
android:
name
=
"android.intent.action.CALL"
></
action
>
</
intent
-
filter
>
</
receiver
>
</
application
>
|
下面是执行代码:发送广播!!
Intent intentAction = new Intent();
intentAction.setAction("bootwizardstart");
sendBroadcast(intentAction);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 |
//模拟拨打电话广播
public
class
MainActivity
extends
Activity
{
@Override
public
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
);
setContentView
(
R
.
layout
.
main
);
//使用intent来传递广播,初始化一个对象
Intent
intent
=
new
Intent
();
//"android.intent.action.CALL"是标识符,用来识别哪些广播可以接受到我发送的广播消息
intent
.
setAction
(
"android.intent.action.CALL"
);
//发送广播
this
.
sendBroadcast
(
intent
);
}
}
|
下面是广播接收者,新建一个类,继承BroadcastReceiver:
1
2
3
4
5
6
7
8
9
10
11
12 |
// 广播接收者
class
Secnd_Recevier
extends
BroadcastReceiver
{
@Override
public
void
onReceive
(
Context
context
,
Intent
intent
)
{
Bundle
bundle
=
intent
.
getExtras
();
// 夜间模式
queryNightModes
.
nightModes
(
sp
,
view
);
}
}
|
发送者发送广播后,广播接收者就可以收到广播,然后就可以在onReceive(Context context, Intent intent)方法中做想要的操作了!
第二种:动态注册。
在Activity中绑定接收者必须依附该应用程序存在,或者一个BroadcastReceiver用于更新UI,就没有必要再程序关闭时接收者还运行,故无需在
AndroidManifest.xml中注册而可以放在Activity中注册。
代码如下:
新建一个类,继承BroadcastReceiver:
1
2
3
4
5
6
7
8
9
10
11
12 |
// 广播接收者
class
Secnd_Recevier
extends
BroadcastReceiver
{
@Override
public
void
onReceive
(
Context
context
,
Intent
intent
)
{
Bundle
bundle
=
intent
.
getExtras
();
// 夜间模式
queryNightModes
.
nightModes
(
sp
,
view
);
}
}
|
然后在代码中注册
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
public
class
MainActivity
extends
Activity
{
@Override
public
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
);
setContentView
(
R
.
layout
.
main
);
// 注册广播接收者
Secnd_Recevier
secnd_Recevier
=
new
Secnd_Recevier
();
IntentFilter
intentFilter
=
new
IntentFilter
(
"nightMode"
);
registerReceiver
(
secnd_Recevier
,
intentFilter
);
}
|
然后再发送者哪里发送广播,接收者就可以接收到啦!当然发送者和接收者的标识符必须一致哦!