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>
    
  • 相关阅读:
    LocalImprove算法
    Improve算法
    CSU-ACM2014年校队选拔赛指导赛解题报告
    CSU-ACM暑假集训基础组训练赛(4)解题报告
    CSU-ACM暑假集训基础组七夕专场
    CSU-ACM暑假集训基础组训练赛(2) 解题报告
    CSU-ACM2014暑假集训基础组训练赛(1) 解题报告
    Aizu 2164 CSUOJ 1436 Revenge of the Round Table
    插头DP小结
    Codeforces 128C Games with Rectangle
  • 原文地址:https://www.cnblogs.com/lzpq/p/13148686.html
Copyright © 2011-2022 走看看