首页主机资讯android sendbroadcast 怎么接收

android sendbroadcast 怎么接收

时间2025-09-26 23:48:04发布访客分类主机资讯浏览997
导读:在 Android 中,发送广播(sendBroadcast)通常是通过 Intent 对象实现的。要接收一个广播,你需要创建一个 BroadcastReceiver 子类并重写 onReceive( 方法。以下是如何创建一个 Broad...

在 Android 中,发送广播(sendBroadcast)通常是通过 Intent 对象实现的。要接收一个广播,你需要创建一个 BroadcastReceiver 子类并重写 onReceive() 方法。以下是如何创建一个 BroadcastReceiver 子类并接收广播的步骤:

  1. 创建一个 BroadcastReceiver 子类:
import android.content.BroadcastReceiver;
    
import android.content.Context;
    
import android.content.Intent;
    
import android.widget.Toast;


public class MyBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    
        // 在这里处理接收到的广播
        String action = intent.getAction();

        if (action.equals("com.example.MY_BROADCAST")) {
    
            Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();

        }

    }

}
    
  1. 在 AndroidManifest.xml 文件中注册 BroadcastReceiver:
<
    manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example">
    

    <
    application
        ...>
    
        ...
        <
    receiver android:name=".MyBroadcastReceiver">
    
            <
    intent-filter>
    
                <
    action android:name="com.example.MY_BROADCAST" />
    
            <
    /intent-filter>
    
        <
    /receiver>
    
    <
    /application>
    
<
    /manifest>
    
  1. 发送广播:

在你的 Activity 或其他组件中,你可以使用以下代码发送广播:

Intent intent = new Intent("com.example.MY_BROADCAST");
    
sendBroadcast(intent);
    

当广播被发送时,MyBroadcastReceiver 的 onReceive() 方法将被调用,你可以在该方法中处理接收到的广播。

声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!


若转载请注明出处: android sendbroadcast 怎么接收
本文地址: https://pptw.com/jishu/709194.html
android sendbroadcast 怎么优化 android sendbroadcast 能干嘛

游客 回复需填写必要信息