如何从BroadcastReceiver打开片段?

时间:2014-10-25 04:00:32

标签: android android-fragments broadcastreceiver

我想通过短信接收器打开片段,我应该如何实现?任何帮助表示赞赏。

接收者源代码:

public class SMSReceiver extends BroadcastReceiver {
    private String body, vsn;

    @Override
    public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();
    if (bundle == null)
        return;

    Object[] pdus = (Object[]) bundle.get("pdus");

    for (int i = 0; i < pdus.length; i++) {
        SmsMessage sms = SmsMessage.createFromPdu((byte[]) pdus[i]);
        body = sms.getMessageBody().toString();
        PaymentTransaksi.setSmsDetail(body);

        Intent showPaymentForm = new Intent();
        showPaymentForm.setClassName("showPaymentForm",
                "id.dutapulsa.bayartagihan.PaymentTransaksi");
        showPaymentForm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
}

这是片段源代码:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    paymentRootView = inflater.inflate(R.layout.payment_main, container,
                false);

    return paymentRootView;
}

1 个答案:

答案 0 :(得分:0)

我知道这个问题很老了,但我想与社区分享我的解决方案,因为这是一项常见任务。

1。)在您的布局文件中(例如您的MainActivity)创建一个容器,该容器将被当前片段替换。

2。)将以下代码片段添加到您的活动中(如果需要,请不要忘记稍微更改一下)

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns1:Clients xmlns:ns1="http://itaintworking.com/test/"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <ns1:clientName>hello</ns1:clientName>
   <ns1:addressDetails>
       <ns1:addressId>98989</ns1:addressId>
   </ns1:addressDetails>
 </ns1:Clients>

3。)现在你可以从BroadcastReceiver中调用这个方法,就像这样:

  public void updateFragment(Class<?> clazz, Bundle args) {
    String tag = clazz.getName();
    FragmentManager fragmentManager = getFragmentManager();
    Fragment fragment = fragmentManager.findFragmentByTag(tag);
    if (fragment == null) {
        fragment = Fragment.instantiate(this, tag, args);
        fragment.setRetainInstance(true);
    }
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.addToBackStack(tag);
    transaction.replace(R.id.container, fragment, tag);
    transaction.commit();
}

4.。)对于我从DialogFragment扩展的对话框,并在我的Activity中有以下方法:

updateFragment(ContentFragment.class, null);

希望我能帮忙! ; - )