安卓第一行代码之全局大喇叭BroadCast

接收广播:


动态接收:

1.设置IntentFilter        IntentFilter filter = new IntentFilter ();   filter.addAction("intent.action.XXX");


2.编写继承自BroadCastReceiver的类。重写OnReceive函数 ,创建实例

public class Receiver extends BroadCastReceiver

{

    public class onReceive(Context context ,Intent intent)

    {

        xxxxx

    }

}

Receiver  receiver = new Receiver();


3.onCreate中注册监听

registerReceiver(receiver ,filter);


4.onDestory中注销监听

unregisterReceiver(receiver );


静态接收:


在manifest中注册

    android:name = ".xxxReceiver"

    android:exported ="true"

    android:enabled = "true">

   

        

    


代码实现:

public class Receiver extends BroadCastReceiver

{

    public class onReceive(Context context ,Intent intent)

    {

        xxxxx

    }

}


发送一般广播:

Intent intent = new Intent ("intent.xxxxx");

Bundle xx = new Bundle();

xx.putExtra("key","value");

intent.setData(xx);

sendBroadCast(intent);

发送有序广播:

sendOrderedBroadCast(intent,null);


在高级别的receiver里可以取消继续广播 AbortBroadCast();


本地广播其实一样,但可以保证广播不会发送到其他应用。只不过要实例化一个LocalBroadCastManager:

LocalBroadCastManager  localManager  = LocalBroadCastManager.getInstance(this);

注册:localManager .registerReceiver(reciver,intent);

注销: localManager.unregisterReciver(reciver,intent);

发送: localManager.sendBroadCast(intent);

你可能感兴趣的:(安卓第一行代码)