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

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="registBR"
        android:text="注册广播接收器" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="unregistBR"
        android:text="解注册广播接收器" />
</LinearLayout>

接收端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);
    }
}

广播发送端代码同上一篇

猜你喜欢

转载自blog.csdn.net/we1less/article/details/107742486