Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use send broadcast method in fragment class

Tags:

android

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

like image 968
user3203211 Avatar asked Jan 20 '14 15:01

user3203211


People also ask

What method is used to send broadcast event?

The sendBroadcast(Intent) method sends broadcasts to all receivers in an undefined order. This is called a Normal Broadcast. This is more efficient, but means that receivers cannot read results from other receivers, propagate data received from the broadcast, or abort the broadcast.

How to send intent to broadcast receiver?

Sending Broadcast intents from the Activity The following snippet is used to send an intent to all the related BroadcastReceivers. Intent intent = new Intent(); intent. setAction("com.

How pass data from Broadcastreceiver to activity in Android?

Intent intent = getIntent(); String message = intent. getStringExtra("message"); And then you will use message as you need. If you simply want the ReceiveText activity to show the message as a dialog, declare <activity android:theme="@android:style/Theme.


1 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()!!!

like image 97
JanBo Avatar answered Oct 15 '22 14:10

JanBo