zoukankan      html  css  js  c++  java
  • android中如何发送一个广播

    1.首先要声明广播

    [java] view plain copy
    1. private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()  
    2. {  
    3.     @Override  
    4.     public void onReceive(Context context, Intent intent) //onReceive函数不能做耗时的事情,参考值:10s以内  
    5.     {  
    6.         Log.d("scott", "on receive action="+intent.getAction());  
    7.         String action = intent.getAction();  
    8.         if (action.equals("com.scott.sayhi"))  
    9.         {  
    10.             showDialog("on receive action="+intent.getAction());  
    11.         }  
    12.     }  
    13. };  

    2.其次要注册广播,有两种方式:xml注册和代码注册

     

    xml注册:

    <receiver Android:name="com.scott.sayhi.MyBroadcastReceiver" >
    <intent-filter>
    <action android:name="com.scott.sayhi" />
    </intent-filter>
    </receiver>

    代码注册:

    IntentFilter filter = new IntentFilter();
    filter.addAction("com.scott.sayhi");
    MyActivity.this.registerReceiver(mBroadcastReceiver, filter);

    上述2个步骤就可以了。

    3.发送广播

    [java] view plain copy
    1. Intent intent = new Intent();  
    2. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
    3. intent.setAction("com.scott.sayhi");  
    4. MyActivity.this.sendBroadcast(intent);  

    4.收听开机广播

    intent-filter设置如下即可

    <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    <category android:name="android.intent.category.HOME" />
    </intent-filter>

  • 相关阅读:
    idea自定义servlet模板
    jsp基础-指令,内置对象,动作,EL表达式,JSTL技术
    cookie和session
    HttpServletRequest
    IO字符流
    IO字节流
    递归
    File 类
    JDBC数据库连接
    Map接口
  • 原文地址:https://www.cnblogs.com/mafeng/p/6726838.html
Copyright © 2011-2022 走看看