Android 在一个片段中广播

Android Broadcast in one Fragment

我正在构建自己的 VoIP 应用程序。最初使用 Activity 和 BroadcastReceiver 并且效果很好,现在我想将它们转换为 Fragment 用于我的抽屉。

因为Fragment无法使用BroadcastReceiver,所以在Whosebug上找了一些方法还是不行...

以下所有代码都在同一个文件中

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        V = inflater.inflate(R.layout.dial, container, false);
        filter = new IntentFilter();
        filter.addAction("android.SipDemo.INCOMING_CALL");
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(callReceiver, filter);
        getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        initializeManager();

        // Inflate the layout for this fragment
        return V;
    }

private final BroadcastReceiver callReceiver = new BroadcastReceiver()
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        SipAudioCall incomingCall = null;
        try {

            SipAudioCall.Listener listener = new SipAudioCall.Listener() {
                @Override
                public void onRinging(SipAudioCall call, SipProfile caller) {
                    try {
                        call.answerCall(30);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                public void onCallEnded(SipAudioCall call) {
                    endMessage();
                }
            };
            incomingCall = manager.takeAudioCall(intent, listener);
            updateStatus("call incoming");
            call = incomingCall;
            call.answerCall(30);
            call.startAudio();
            call.setSpeakerMode(isSpeakerClicked);
        } catch (Exception e) {
            if (incomingCall != null) {
                incomingCall.close();
            }
        }
    }
};

In your Fragment :

在您的 onCreateView

中调用 registerBroadcast()
private void registerBroadcast() {
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(addCallReceiver,
                new IntentFilter(getString(R.string.broadcast_add_call)));
    }

BroadcastReceiver addCallReceiver= new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // perform actions
    }
};

From where you want to trigger receiver :

LocalBroadcastManager.getInstance(mContext).sendBroadcast(new Intent(getString(R.string.broadcast_add_call)));