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

时间:2015-12-09 19:22:19

标签: android broadcastreceiver send broadcast

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

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) {}
    }
}

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

2 个答案:

答案 0 :(得分:3)

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

我不确定您为何要向同一个班级广播,但您也可以在registerReceiver()之前调用onCreate()方法来解决您的问题。 sendBroadcast()致电。

答案 1 :(得分:0)

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

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"/>