Broadcast(发送自定义广播)

Layout




    

先定义一个广播接收器

package com.example.hzx.my_custom_broadcast;

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

/**
 * Created by hzx on 2018/11/6.
 */

public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"received in MyBroadcastReceiver",Toast.LENGTH_SHORT).show();
    }
}

MainActivity

public class MainActivity extends AppCompatActivity {

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

        Button button = (Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
                sendBroadcast(intent);
            }
        });
    }
}

注意:
1、 在AndroidManifest.xml中对广播接受进行修改


image.png

效果:
当点击按键时,提示"received in MyBroadcastReceiver"

上面的实现是无序广播,如果需要修改为有序广播


image.png

你可能感兴趣的:(Broadcast(发送自定义广播))