BroadcastReceiver静态和动态注册简单Demo

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/blackzhangwei/article/details/51948138

清单文件注册与代码注册:
<1>优先高的先执行,如果相同,那么代码优先。
<2>代码注册必须在所依赖的界面正常显示时起作用,通常关闭后解除
<3>清单文件注册,在启动后会一直有效,所以相对代码注册范围更大

onReceive方法:会在主线程中执行,该执行不要超过10秒,否则超时异常,不要在该方法中实现弹窗等操作。一般此方法我们会执行比较简单短小的操作。通常可以配合通知一起使用。

为了区分用了2个Receiver,
Receiver_1静态注册、Receiver_2动态注册

静态清单文件配置:

        <receiver android:name=".Receiver_1">//静态注册
            <intent-filter>
                <action android:name="Action_1"/>
            </intent-filter>
        </receiver>

代码:

package com.moliying.black.broadcastreceiverdemo;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends AppCompatActivity {
    Receiver_2 receiver;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver = new Receiver_2();//new出来动态注册的接收器
    }

    public void click(View v) {
        switch (v.getId()) {
            case R.id.button://发送一条静态注册普通广播
                Intent intent = new Intent();
                intent.putExtra("key", "静态注册");
                intent.setAction("Action_1");
                sendBroadcast(intent);//发送广播
                break;
            case R.id.button2://发送一条动态注册普通广播
                Intent intent2 = new Intent();
                intent2.putExtra("key", "动态注册");
                intent2.setAction("Action_2");
                sendBroadcast(intent2);
                break;
        }
    }


    protected void onResume() {
        super.onResume();
        //获取一个过滤器
        IntentFilter filter = new IntentFilter();
        filter.addAction("Action_2");
        registerReceiver(receiver,filter);//注册
    }


    protected void onStop() {
        super.onStop();
        unregisterReceiver(receiver);//解除注册
    }
}

静态接收:

package com.moliying.black.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * 静态注册实例
 */
public class Receiver_1 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String key = intent.getStringExtra("key");
        Toast.makeText(context, key+"成功", Toast.LENGTH_SHORT).show();

    }
}

动态接收:

package com.moliying.black.broadcastreceiverdemo;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

/**
 * 动态注册
 */
public class Receiver_2 extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, "动态注册成功", Toast.LENGTH_SHORT).show();
    }
}
展开阅读全文

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