Android Fragment - BroadcastReceiver调用 fragment 方法

标签 android android-fragments broadcastreceiver android-broadcastreceiver

我有一个 BroadcastReceiver,它接收发送到 Fragment 的广播。 我正在接收广播,但如何从 Fragment 本身调用方法? 我基本上需要在广播到达后更新一个列表,列表和更新方法是 fragment 的一部分。

public class FragmentReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(action != null && action.equals("AllTasksFragmentUpdate"))
        {
            //
        }
    }
}

注册接收器:

    @Override
public void onCreate(final Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    getActivity().registerReceiver(new FragmentReceiver(), new IntentFilter("AllTasksFragmentUpdate"));
}

如何从 fragment 中调用方法?

最佳答案

您可以通过以下方式实现您的广播接收器:

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.adobe.libs.connectors.R;

public class YourFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater,
                                @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        //Start listening for refresh local file list   LocalBroadcastManager.getInstance(getActivity()).registerReceiver(mYourBroadcastReceiver,
                new IntentFilter(<YOUR INTENT FILTER>));

        return inflater.inflate(R.layout.your_fragment_layout, null, true);
    }

    @Override
    public void onDestroyView() {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(mYourBroadcastReceiver);
    }

    private final BroadcastReceiver mYourBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            // Now you can call all your fragments method here
        }
    };
}

关于Android Fragment - BroadcastReceiver调用 fragment 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35996963/

相关文章:

android - 如何在我的 xml 文件中显示自定义 View ?

java - 当屏幕太大时出现错误

android - 无法在 AndroidStudio 中导入 android-async-http

java - 在不使用任何资源 xml 的情况下将 View (按钮、标签等)添加到动态 fragment

java - Android应用程序开发中录音后无法保存音频文件

android - 电话状态改变了监听器从未被解雇

android - 如何处理android中每天触发的警报

android - 使用定制相机的方形图像

java - 无法更新 fragment View 中的数据

android - 如何将处理程序传递给 LocalBroadcastManager.registerReceiver(...)