如何将数据从广播接收器发送到片段?

时间:2018-11-13 06:56:28

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

如何从广播接收器发送数据以分段?在这里,我想将电话号码(OriginatingAddress)发送到另一个片段。

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String phonenumber = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + phonenumber + "\n";
            smsMessageStr += smsBody + "\n";                                
        }                                                                  
    }
}

2 个答案:

答案 0 :(得分:0)

只需在片段中注册另一个广播接收器。当您的Fragment附加到Activity并位于前台时,下面的注释代码将起作用。

如果您想在应用未运行时将数据发送到Fragment,则需要在状态栏上显示通知,并将数据附加到未决的NotificationIntent中。作为目标,您需要指定保存感兴趣的Fragment的Activity类,然后在Activity的onCreate中手动提取数据并将其传递给Fragment。

在您的片段中:

// receiver as a global variable in your Fragment class
private BroadcastReceiver messagesReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent != null && intent.getExtras() != null) {
            String smsMessageStr = intent.getExtras().getString("smsMessageStr");
            if (smsMessageStr != null && ! smsMessageStr()) {
                // do what you need with received data
            }
        }
    }
};

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // ...
}

@Override
public void onResume() {
    super.onResume();
    if (getActivity() != null) {
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(messagesReceiver,
                new IntentFilter("your_intent_filter"));
    }
}

@Override
public void onPause() {
    super.onPause();
    if (getActivity() != null) {
        LocalBroadcastManager.getInstance(getActivity()).unregisterReceiver(messagesReceiver);
    }
}

之所以在onResumeonPause方法中注册和注销广播接收器,是因为我们不希望Fragment接收数据并在其处于前台时对其采取行动。 link

中的更多内容

在您的BroadcastReceiver中:

public void onReceive(Context context, Intent intent) {
    Bundle intentExtras = intent.getExtras();
    if (intentExtras != null) {
        Object[] sms = (Object[]) intentExtras.get(SMS_BUNDLE);
        String smsMessageStr = "";
        for (int i = 0; i < sms.length; ++i) {
            SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) sms[i]);

            String smsBody = smsMessage.getMessageBody().toString();
            String phonenumber = smsMessage.getOriginatingAddress();

            smsMessageStr += "SMS From: " + phonenumber + "\n";
            smsMessageStr += smsBody + "\n";   

            // send data only if we have smsMessageStr
            Intent newIntent = new Intent("your_intent_filter");
            newIntent.putExtra("smsMessageStr", smsMessageStr);
            LocalBroadcastManager.getInstance(this).sendBroadcast(newIntent);                             
        }                                                                  
    }
}

答案 1 :(得分:0)

There can be two approaches to send data to Fragment in the current scenario.

Approach One:

You can register the BroadcastReceiver to the activity that is hosting the Fragment and after receiving the Data in onReceive() you can call the Fragment method from an Activity like below:

ExampleFragment fragment = (ExampleFragment)getFragmentManager().
findFragmentById(R.id.example_fragment);
fragment.<specific_function_name_of_that_fragment>();

Approach Two:

You can directly register the BroadcastReceiver in Fragment and then call the fragment method defined there like below:

private final BroadcastReceiver broadCastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          //receive your data here
        }
    };

and then in onCreateView() Register BroadcastReceiver in Fragment like this :

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        LocalBroadcastManager.getInstance(getActivity()).registerReceiver(broadCastReceiver,
                new IntentFilter("YOUR.INTENT.FILTER"));

        return inflater.inflate(R.layout.fragment_sub_categories, container, false);
    }

and then in onDestroyView() unRegister BroadcastReceiver in Fragment like this :

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

Keep In Mind:

Fragment lifecycle will play an important role here. For receiving the Broadcast your Fragment needs to be Created and visible to the User. When Fragment will be destroyed or not Visible to the User then you won't receive the Broadcast.