Android 如何在 onCreate 方法上发送广播消息

How to send broadcast message on onCreate method in Android

我想向应用程序发送广播消息,然后从当前 activity 接收它。我可以发送广播消息,但无法从广播接收器接收到它。这是我的代码;

public class LogIn extends Activity {

    private BroadcastReceiver receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                //toast message received !
            }
        };

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

        ActionBar actionBar = getActionBar();
        //send broadcast message
        Intent i = new Intent(LogIn.class.getName());
        getContext().sendBroadcast(i);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, new IntentFilter(LogIn.class.getName()));
    }

    @Override
    protected void onPause() {
        super.onPause();
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {}
    }
}

我错过了什么问题?谢谢你的帮助..

您正在以不同的意图注册接收器并以不同的意图发送广播。这就是为什么你没有收到你的广播。

public class LogIn extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getActionBar();
    //send broadcast message
    Intent i = new Intent("com.abc");
    getContext().sendStickyBroadcast(i);
}
private BroadcastReceiver receiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
        //toast message received !
        }
    };
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(receiver, new IntentFilter("com.abc"));
}
@Override
protected void onPause() {
    super.onPause();
    try {
        unregisterReceiver(receiver);
    } catch (Exception e) {
    }
}

添加权限

<uses-permission android:name="android.permission.BROADCAST_STICKY"/>

查看 Activity's lifecycle 的图表。 onCreate() 方法在 onResume() 之前运行,因此您在注册接收器之前发送广播。

我不确定你为什么要广播到同一个 class,但你也可以通过调用 onCreate() 中的 registerReceiver() 方法来解决你的问题,在 sendBroadcast() 调用之前。