Broadcast创建动态广播

其实本节与静态结构区别不大

首先创造接收类继承BroadcastReceiver

public class MyR2eceive extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("MESSAGE");
        Log.i("godv", "MyR2eceive--接收广播" + message);
    }

    public MyR2eceive() {
        Log.i("godv", "MyR2eceive--创建");
    }
}

main-xml




    

接收端activity代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    private MyR2eceive r2eceive;

    public void registBR(View v) {
        if (r2eceive == null) {
            r2eceive = new MyR2eceive();
//action
            IntentFilter filter = new IntentFilter("godv");
            registerReceiver(r2eceive, filter);
            Toast.makeText(this, "注册广播接收器", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "已经存在广播接收器", Toast.LENGTH_SHORT).show();
        }

    }

    public void unregistBR(View v) {
        if (r2eceive != null) {
            unregisterReceiver(r2eceive);
            r2eceive = null;
            Toast.makeText(this, "解除注册广播接收器", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "尚未注册广播接收器", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregistBR(null);
    }
}

广播发送端代码同上一篇

你可能感兴趣的:(安卓基础学习,android)