广播接收器的两种注册方式:

1)动态注册:在代码中注册,创建一个IntentFilter(意图过滤器)对象,设置想要就收的广播,在onCreate()方法中通过调用registerReceiver()方法来注册广播接收器,在onDestroy()方法中通过调用unregisterReceiver()方法来注销广播接收器。

2)静态注册:在AndroidManifest.xml文件中注册,<Receiver>标签注册类,通过<IntentFilter>标签中的<Action>来过滤意图。静态注册的好处是,当程序关闭或者没有打开的时候,同样可以接收相关的广播。比如实现开机启动

面试:生命周期

1)广播接受者的生命周期是非常短暂的,在接收到广播的时候创建,onReceive()方法结束之后销毁

2)广播接受者中不要做一些耗时的工作,否则会弹出Application No Response错误对话框

3)最好也不要在广播接受者中创建子线程做耗时的工作,因为广播接受者被销毁后进程就成为了空进程,很容易被系统杀掉

4)耗时的较长的工作最好放在服务中完成

*无序广播

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.administrator.broadcastreceiver.MyBroadcastReceiver"></action>
</intent-filter>
</receiver>
</application>
public void send(View v){
Intent intent = new Intent();
intent.putExtra("name","王者");
intent.putExtra("age",27);
intent.setAction("com.example.administrator.broadcastreceiver.MyBroadcastReceiver");
sendBroadcast(intent);
}
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("name");
int age = intent.getIntExtra("age",30);
Log.i("Main",name+"--"+age);
}
}

*有序广播

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver1">
<intent-filter android:priority="200">
<action android:name="com.example.adminastrator.broadcastreceiver.MyBroadcastReceiver"></action>
</intent-filter>
</receiver>
<receiver android:name=".MyBroadcastReceiver2">
<intent-filter android:priority="100">
<action android:name="com.example.adminastrator.broadcastreceiver.MyBroadcastReceiver"></action>
</intent-filter>
</receiver>
</application>
public void send(View v){
Intent intent = new Intent();
intent.putExtra("name","王者");
intent.setAction("com.example.adminastrator.broadcastreceiver.MyBroadcastReceiver");
sendOrderedBroadcast(intent,null);
}
public class MyBroadcastReceiver1 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("name");
// abortBroadcast(); //拦截广播
setResultData("哈哈"); //发送给优先级低的程序
Log.i("Main",name+"----1");
}
}
public class MyBroadcastReceiver2 extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getStringExtra("name");
String data = getResultData();
Log.i("Main",name+"-"+data+"----2");
}
}

*自动回复短信

<uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>
<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.SEND_SMS"/> <application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.broadcastReceiver.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>
<receiver android:name="com.example.broadcastReceiver.MyReceiver">
<intent-filter android:priority="500">
<action android:name="android.provider.Telephony.SMS_RECEIVED"/>
</intent-filter>
</receiver>
</application>
public class MyReceiver extends BroadcastReceiver {

    @Override
public void onReceive(Context context, Intent intent) {
System.out.println("有短信来了");
Bundle bundle = intent.getExtras();
Object[] objs = (Object[]) bundle.get("pdus");
for (Object obj : objs) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) obj);
String str = sms.getMessageBody();
String phone = sms.getOriginatingAddress();
Log.i("aaaaaaaaaaaa", phone+":"+str);
if("114".equals(phone)){
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(phone, null, "fuck you", null, null);
}
}
}
}

* 外拨电话添加前缀

public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
//收到外拨电话。
String phone = getResultData();
String name = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
setResultData("10193"+phone);
System.out.println("有外拨电话");
Log.i("Main",phone);
}
}

* 监听网络状态

<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission> <application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver">
<intent-filter android:priority="100">
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"></action>
</intent-filter>
</receiver>
</application>
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if(networkInfo == null || !networkInfo.isConnected()){
Log.i("Main","没有网络");
}else{
Log.i("Main","有网络");
}
}
}

*监听网络状态(动态注册)

private MyReceiver myReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceiver = new MyReceiver();
} @Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(myReceiver,filter);
} @Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myReceiver);
} class MyReceiver extends BroadcastReceiver{ @Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Service.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if(networkInfo == null||!networkInfo.isConnected()){
Log.i("Main","没有网络");
}else{
Log.i("Main","有网络");
}
}
}

* 开机自启动

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyBroadcastReceiver">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
</application> 
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent();
intent1.setClass(context,MainActivity.class);
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent1);
}
}

BroadcastReceiver广播接受者的更多相关文章

  1. Android BroadcastReceiver广播接受者

    静态注册 配置清单表注册:只要曾经注册过哪怕关闭也能调用  方式一:sendBroadCastReceive   广播的步骤:       发送  无序广播,普通广播       (1).发送方    ...

  2. BroadcastReceiver广播接受者简单使用

    1.注册BrocadcastReceiver <receiver android:name=".FirstReceiver" > <!-- 指定能够接收的广播类型 ...

  3. BroadcastRecevier广播接受者

    广播接收器的两种注册方式: 1)动态注册:在代码中注册,创建一个IntentFilter(意图过滤器)对象,设置想要就收的广播,在onCreate()方法中通过调用registerReceiver() ...

  4. Android四大组件之一:BroadCastReceiver(广播接收者)

    广播接受者是(BroadCastReceiver)是Android中的地大组件之一,之前学习了一些关于BroadCastReceiver方面的知识,今天回过头来发现已经快忘记的差不多了,毕竟现在是刚开 ...

  5. android84 广播接受者

    #广播接收者(广播接受者进程关闭了也能接收到广播,系统会在清单文件中找哪个广播接受者可以收到这条广播,然后去启动这个接受者的进程,找不到则广播发了就发了没人收到而已) * 现实中:电台要发布消息,通过 ...

  6. 在Service中使用广播接受者

    1.清单文件 <service android:name="com.example.callmethod.MyService"></service> 2.开 ...

  7. Android初级教程IP拨号器初识广播接受者

    需求:输入ip号码并且保存在本地,监听打电话广播,如果电话号码以0开头,则加上ip区号拨打. 首先定义一个页面布局: <LinearLayout xmlns:android="http ...

  8. Android 学习笔记 BroadcastReceiver广播...

    PS:不断提升自己,是件好事... 学习内容: 1.BroadcastReceiver的使用.. 2.通过BroadcastReceiver去启动Service... 1.BroadcastRecei ...

  9. Android的BroadcastReceiver 广播 短信拦截

    如何去理解BroadcastReceiver(广播)?其实可以这样想,首先我们要有一个发送广播的"媒体",在这个例子中,我们暂且用activity组件作为这个媒体,当然以后会用到s ...

随机推荐

  1. rest framework错误笔记——AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly on a view that does not set `.queryset` or have a `.get_queryset()` method.

    用到@api_view装饰器时,访问路由查看api数据时,报错: AssertionError: Cannot apply DjangoModelPermissionsOrAnonReadOnly o ...

  2. TypeError: Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

    这个问题说的很清楚,就是类型不对,需要转化类型,首先讲一下这个问题是在使用pandas的resample函数激发的,官方文档解释的较为清楚,如下: Convenience method for fre ...

  3. 使用xmanager图形化远程连接rhel6

    使用xmanager图形化远程连接rhel6 xmanager中Xbrowser可以提供图形化桌面远程.和vnc比,可以类似于本地一样用户切换. 操作步骤: linux服务端: 1:查看/etc/in ...

  4. Ubuntu/Debian 8 安装 Intel realsense 摄像头驱动

    ## Make Ubuntu/Debian Up-to-date1. sudo apt-get update && sudo apt-get upgrade && su ...

  5. .NET中制做对象的副本(三)通过序列化和反序列化为复杂对象制作副本

    1.类的定义 /// <summary> /// 学生信息 /// </summary> [Serializable] public class Stu { /// <s ...

  6. python2和3使用pip时的问题

    win10,电脑之前装有Anaconda,python2.因为需要用到python3,所以直接下载安装了python3.python3默认路径在c盘.我将其移到D盘并修改了两个环境变量.这时电脑的默认 ...

  7. Linux中涉及到计算优先级及其他问题

    比如计算矩形周长: a= b= echo `expr \* $((a+b))` 1.expr外要使用反引号,且expr只支持整数计算,如果涉及到浮点数计算要采用下面方法 2.优先计算a+b时,要使用双 ...

  8. Spark的HA部署

    一.安装JDK.Scala 二.安装zookeeper 三.安装Hadoop 四.安装Spark 1.修改spark/conf/spark-env.sh export JAVA_HOME=/usr/j ...

  9. hdu3193 降维+rmq

    /* 给定n个数对(p,d),如果有这么一个数对(pi,di),其他所有的数对都不能严格小于这个数对 请求出有多少个这样的数对! 解法:对于数对(p,d),能找到在[1,p-1]之间的小于d的数对,那 ...

  10. python+selenium五:多窗口切换与获取句柄

    from selenium import webdriverfrom selenium.webdriver.common.by import Byimport time driver = webdri ...