1.定义广播接收者
- 定义类继承BroadcastReceiver,重写onReceive方法
getResultData(); 获取Date
setResultDate();
生命周期:
- 广播接收者的生命周期是非常短暂的,在接收到广播的时候创建,onReceive()方法结束之后销毁
例1:监听打电话
1.OutCallReceiver 类
public class OutCallReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
String number = getResultData();
System.out.println("电话:" + number);
setResultData("12340" + number);
}
}
2. 在清单文件中声明
<receiver android:name="com.example.recivertest.OutCallReceiver">
<intent-filter >
<!-- 打电话的动作 -->
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
注意:一定要加权限
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
例2.在代码中注册
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registReceiver();
}
private void registReceiver() {
receiver = new OutCallReceiver();
IntentFilter filter = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
this.registerReceiver(receiver, filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(receiver);
}
注意:一定要调用取消注册receiver的方法,不然会后台会报错。
这种方式通常与service使用,在service中注册receiver,这样receiver的生命周期就与service相同。而清单文件中注册,就算应用退出,receiver也一直有效。