目 录
广播接收者简介
广播接收者入门
广播接收者的创建
package cn.lwx.broadcastreceiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class MyReceiver extends BroadcastReceiver {
@Override//在该方法中实现广播接收者的相关操作
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
throw new UnsupportedOperationException("Not yet implemented");
}
}
静态注册
动态注册
package cn.lwx.broadcastreceiver;
import androidx.appcompat.app.AppCompatActivity;
import android.content.IntentFilter;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
private MyReceiver receiver;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
receiver = new MyReceiver();//ctrl+alt+f 快速将局部变量提升为 成员变量
//实例化过滤器并设置要过滤的广播
String action = "android.provider.Telephony.SMS_RECEIVED";
IntentFilter intentFilter = new IntentFilter(action);
registerReceiver(receiver, intentFilter);//注册广播
}
//当Activity销毁时,取消注册
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
}
实战演练——拦截史迪仔电话
项目工程---源码:https://gitee.com/lwx001/BroadcastReceiver
可用gitee直接拷贝。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.lwx.broadcastreceiver">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!--注册广播接收者-->
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
</manifest>