Android 动态发送广播接收


import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";

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

        SettingBroadcastReceiver settingBroadcastReceiver = new SettingBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.test");
        registerReceiver(settingBroadcastReceiver, intentFilter);


        Button btn = findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e(TAG, "onClick: ------------------send-----------------------");
                Intent intent = new Intent();
                intent.setAction("android.test");
                //intent.putExtra("sele","11111");
                sendBroadcast(intent);
            }
        });
    }


    class SettingBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("android.test")) {
                Log.e(TAG, "onReceive: ---------------SettingBroadcastReceiver-------------------");
            }
        }
    }
}

你可能感兴趣的:(android)