zoukankan      html  css  js  c++  java
  • Android学习笔记BroadcastReceiver(广播接收者)

    Android发送广播的过程

    代码实现

    MainActivity.java

    import androidx.appcompat.app.AppCompatActivity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.Button;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Button button = findViewById(R.id.btn_Broadcast);//获取广播按钮
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction("马云");
                    //为Itent添加动作zuckerg
                    sendBroadcast(intent);//发送广播
                }
            });
        }
    }   
    

    MyReceiver.java

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.widget.Toast;
    
    public class MyReceiver extends BroadcastReceiver {
        private static final String ACTIONI = "马云";//动作1
        private static final String ACTION2 = "小腾腾";
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(ACTIONI)){//回复第一个广播
                Toast.makeText(context,
                        "MyReceiver收到:马云的广播",
                        Toast.LENGTH_SHORT).show();
            }else if(intent.getAction().equals(ACTION2)){//回复第二个广播
                Toast.makeText(context,"MyReceiver收到:小腾腾的广播",
                        Toast.LENGTH_SHORT).
                        show();
            }
        }
    }
    

    AndroidManifest.xml清单文件注册BroadcastReceiver

            <!--
                 注册广播接收器
                 android:enabled="true"可以被实例化
                 android:exported="true"能接收其他app的广播
             -->
            <receiver
                android:name=".MyReceiver"
                android:enabled="true"
                android:exported="true"
                tools:ignore="WrongManifestParent">
                <intent-filter>
                    <!--配置允许接收的Action-->
                    <action android:name="马云"/>
                    <action android:name="小腾腾"/>
                </intent-filter>
            </receiver>
        </application>
    
  • 相关阅读:
    Saltstack自动化操作记录(1)-环境部署
    Centos下堡垒机Jumpserver V3.0环境部署完整记录(1)-安装篇
    Centos7修改默认网卡名(改为eth0)以及网卡启动报错RTNETLINK answers: File exists处理
    Python下操作Memcache/Redis/RabbitMQ说明
    libsm6 & libgtk lost (QQ + WPS: Ubuntu)
    Android中View绘制优化
    Android ListView 几个重要属性
    Android Layout_weight 属性
    Java关键字final、static使用总结
    Android 事件
  • 原文地址:https://www.cnblogs.com/lzpq/p/13148686.html
Copyright © 2011-2022 走看看