Android---发送自定义广播

发送自定义广播既是正常理解中的第三方应用广播。

1、首先定义一个控件,绑定点击事件,在点击事件中添加方法。
    /**
     * 发送自定义的广播
     */
    private void sendCustomBroadcast() {
        Intent intent = new Intent();
        intent.putExtra("message","恭喜你,成功接收到发送的广播");
        intent.setAction("com.android.example.CUSTOM_BROADCAST");
        sendBroadcast(intent);
    }

2、创建一个广播接收者,继承BroadcastReceiver,并重写onReceive方法
    /**
     * 创建一个广播接收者,接收发送的自定义广播
     */
    public class MyCustomBroadcastReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.android.example.CUSTOM_BROADCAST")) {
                String message = intent.getStringExtra("message");
                Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
            }
        }
    }

3、在MainActivity中进行动态注册
    /**
     * 注册一个广播接收者
     */
    private void registerCustomBroadcastReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.android.example.CUSTOM_BROADCAST");
        mMyCustomBroadcastReceiver = new MyCustomBroadcastReceiver();
        registerReceiver(mMyCustomBroadcastReceiver,intentFilter);
    }
    
4、动态注册的广播,记得取消注册,否则可能会引起内存溢出

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMyCustomBroadcastReceiver != null) {
            unregisterReceiver(mMyCustomBroadcastReceiver);
        }
    }

Android---发送自定义广播_第1张图片

你可能感兴趣的:(Android开发,android,android,studio)