android studio广播

简单使用

步骤:

  1. 发送一条广播
//发送一条广播
//动作
                Intent intent=new Intent("sunweihao");
                //发送广播
                sendBroadcast(intent);
  1. 接收广播:
public class MyBroadcastReceiver extends BroadcastReceiver {
    
    
    private static final String  ACTION1="sunweihao";
    private static final String  ACTION2="sunweihao2";
    @Override
    public void onReceive(Context context, Intent intent) {
    
    
    //根据广播来进行逻辑处理
        if (ACTION1==intent.getAction()) {
    
    
            Toast.makeText(context, "孙伟豪", Toast.LENGTH_SHORT).show();
        }else if (ACTION2==intent.getAction()) {
    
    
            Toast.makeText(context, "孙伟豪2", Toast.LENGTH_SHORT).show();
        }

    }
}
  1. 注册广播
<!--注册广播
        表示可实例化
        表示可以被其他应用接收
        -->
        <receiver android:name=".MyBroadcastReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="sunweihao"/>
                <action android:name="sunweihao2"/>
            </intent-filter>

        </receiver>

猜你喜欢

转载自blog.csdn.net/sunweihao2019/article/details/108849224