zoukankan      html  css  js  c++  java
  • BroadcastReceiver组件

    BroadcastReceiver  广播接收者   必须指定要接收的广播类型。必须明确的指定action
     
    广播:事件。
    普通广播: 是异步的。会广播接收者同时接收,不能被中断
    sendBroadcast()
    有序广播: 是同步的。会根据广播接收的优先级进行接收,是可以中断   短信到来广播 
    sendOrderBroadcast()
    -1000 ~ 1000
    如果有序广播明确的指定了广播接收者,他是无法被中断的。
     
    广播接收者订阅的两种方式:
    1 在清单文件里面指定:
    1         <receiver android:name=".SmsReceiver">
    2             <intent-filter android:priority="1000">
    3                 <action android:name="android.provider.Telephony.SMS_RECEIVED"/>
    4             </intent-filter>
    5         </receiver>
    2 在代码里面指定
    1     IntentFilter filter = new IntentFilter();
    2     filter.setPriority(1000);
    3     filter.addAction("android.provider.Telephony.SMS_RECEIVED");
    4     registerReceiver(new SmsReceiver(), filter);

    onReceive()方法里面是不能执行耗时的操作,这个方式如果在10s之内没有执行完毕,就anr.

    自定义广播:
      在MainActivity中代码如:
      
    1     public void send(View v){
    2      String info = et_info.getText().toString();
    3      
    4      //发送广播
    5      Intent intent = new Intent();
    6      intent.setAction("cn.itcast.action.send");
    7      intent.putExtra("info", info);
    8      sendBroadcast(intent);  //发出的是普通广播
    9     }

    写一个类继承BroadcastReceiver并且在清单文件中配置:

     1 public class MyReceiver extends BroadcastReceiver {
     2      @Override
     3      public void onReceive(Context context, Intent intent) {
     4         // TODO Auto-generated method stub
     5 
     6         String info = intent.getStringExtra("info");
     7          Log.i("i", "info :" + info);
     8      }
     9 
    10 }
    1         <receiver android:name=".MyReceiver">
    2             <intent-filter>
    3                 <action android:name="cn.android.action.send"/>
    4             </intent-filter>
    5         </receiver>
  • 相关阅读:
    maven中net.sf.json报错的解决方法(转载)
    [PY3]——环境配置(1)——pyenv | pip | ipython | jupyter(含安装pyenv环境shell脚本)
    [LNMP]——LNMP环境配置
    Tomcat
    Amoeba+Mysql 实现读写分离
    LVS+keepalived DR模式配置高可用负载均衡集群
    [Mysql高可用]——双主互备+keepalived
    Mysql 日志管理
    Mysql基本操作总结
    [Mysql]——通过例子理解事务的4种隔离级别
  • 原文地址:https://www.cnblogs.com/androidez/p/2887107.html
Copyright © 2011-2022 走看看