Home » Android » android – how to use send broadcast method in fragment class

android – how to use send broadcast method in fragment class

Posted by: admin June 15, 2020 Leave a comment

Questions:

I need a little bit of help. I’m trying on the gps on a mobile. No idea whether that works or not but before that I have set onclicklistener for the button but it does not allow to have sendbroadcast. Anyone have solution for this?

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;

}

}

any other alternative to use the intent …m stuck a bit as m using swipeable tabs so dono much around that,any help is much appreciated

How to&Answers:

What you need is this code:

   getActivity().sendBroadcast(intent);

Edit 1: Some explanation -> Fragments are attached to an Activity, which is a subclass of Context which is required for sendBroadcast. So with getActivity().sendBroadcast() you will use the Context associated with Activity the Fragment is attached to at the moment.

Edit 2: I see in your Toast you are using Gloabal.getcontext(), replace that with getActivity()!!!