如何在片段类中使用send broadcast方法

时间:2014-01-20 15:00:42

标签: android

我需要一些帮助。我在手机上尝试gps。不知道这是否有效但在此之前我已经为按钮设置了onclicklistener但它不允许有sendbroadcast。有人有解决方案吗?

public class locate extends Fragment {
    Button b1;

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

    View rootView = inflater.inflate(R.layout.locate, container, false);
    onCreate(savedInstanceState);
    b1=(Button)rootView.findViewById(R.id.widget33);
    b1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
            Toast.makeText(Gloabal.getcontext(), "text", Toast.LENGTH_LONG).show();
            Intent intent=new Intent("android.location.GPS_ENABLED_CHANGE");
            intent.putExtra("enabled", true);
            sendBroadcast(intent);
            //startActivity(intent);
        }
    });
    return rootView;

}

}

使用意图的任何其他替代方案... m使用可滑动标签卡住了一点,所以不要太多了,任何帮助都非常感谢

1 个答案:

答案 0 :(得分:18)

您需要的是此代码:

   getActivity().sendBroadcast(intent);

编辑1: 一些解释 - >片段附加到Activity,它是Context的子类,是sendBroadcast所必需的。因此,使用getActivity()。sendBroadcast(),您将使用与片段附加的活动相关联的上下文。

编辑2: 我在您的Toast中看到您正在使用Gloabal.getcontext(),将其替换为getActivity()!!!