BroadcastReceiver(二)手动注册注销receiver

1.在 AndroidManifest.xml 中删除 相关receiver的配置标签

2.手动的receiver代码 

public class LReceiver extends BroadcastReceiver {


    //这里为何要用 intent.action. ?
    public static final String ACTION = "com.example.kfk.lbroadcastreceiver.intent.action.LReceiver";
//    public static final String ACTION = "com.example.kfk.lbroadcastreceiver.LReceiver";//也可以
    public LReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {

        System.out.println("接收器L 收到了消息:"  + intent.getStringExtra("msg"));
    }
}


2.手动注册

<span style="white-space:pre">	</span>receiver = new LReceiver();
        IntentFilter filter = new IntentFilter(LReceiver.ACTION);
        filter.setPriority(1);
        registerReceiver(receiver,filter);

3.发送消息

<span>	</span>Intent i2 = new Intent(LReceiver.ACTION);//隐式启动
        i2.putExtra("msg","回家睡觉!");
        sendBroadcast(i2);//发送消息,不可被中断

4.手动注销

unregisterReceiver(receiver);


展开阅读全文

没有更多推荐了,返回首页