【问题标题】:Broadcast receiver in Fragment?片段中的广播接收器?
【发布时间】:2016-03-12 17:52:27
【问题描述】:

我使用广播接收器,并在 Fragment.java 中注册。但它不起作用。 我的代码:

Intent intent = new Intent("android.intent.action.LOGIN");
intent.putExtra("message", obj.getToken());
intent.setAction("com.sunrise.android.LOGIN");
loginView.getContext().sendBroadcast(intent);

在片段中:

@Override
public void onResume() {
    super.onResume();
    informationStudentPresenter = new InformationStudentPresenter(this);
    IntentFilter intentFilter = new IntentFilter("android.intent.action.LOGIN");
    getActivity().registerReceiver(broadcastReceiver, intentFilter);
}
 private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(getActivity(), "CLGT", Toast.LENGTH_SHORT);
    if(intent.getAction().equalsIgnoreCase("com.sunrise.android.LOGIN")){
            if(!"".equals(findToken())) {
                informationStudentPresenter.getProfileStudent();
                informationStudentPresenter.showToast();
            }
       }
    }
};

你能告诉我我的错误在哪里以及如何解决它吗? 谢谢。

【问题讨论】:

    标签: android android-fragments broadcastreceiver broadcast android-broadcast


    【解决方案1】:

    在使用不同的名称初始化 Intent 后,您正在更改 Intent 的操作名称。然后,您将使用等待旧操作名称的 IntentFilter 注册广播接收器。

    【讨论】:

    • 对不起,你的意思是 inten.setAction("android.intent.action.LOGIN"); ?
    • 你给Intent的构造函数的字符串是你在setAction中覆盖的字符串,是你给IntentFilter的字符串。
    • 并且不需要在 onReceive 方法中检查名称,前提是您有 IntentFilter 期望正确的操作名称。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-05
    • 1970-01-01
    • 2014-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多