美文网首页
Broadcast(发送自定义广播)

Broadcast(发送自定义广播)

作者: 昨天剩下的一杯冷茶 | 来源:发表于2018-11-06 11:05 被阅读3次

    Layout

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context="com.example.hzx.my_custom_broadcast.MainActivity">
    
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send Broadcasts"/>
    
    </LinearLayout>
    
    

    先定义一个广播接收器

    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(发送自定义广播)

          本文链接:https://www.haomeiwen.com/subject/zewyxqtx.html