How to use broadcast and receivers

2019-08-19 18:54发布

How can I use my Broadcast receiver? Like when my app starts how do I make the receiver continually run its code?

My Reciver code:

  private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        ConnectivityManager mConnectivity;
        mConnectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo info = mConnectivity.getActiveNetworkInfo();
        if (info == null || !mConnectivity.getBackgroundDataSetting()) {

            wifi.setChecked(false);

            return;
        } else {
            int netType = info.getType();
            //int netSubtype = info.getSubtype();
            if (netType == ConnectivityManager.TYPE_WIFI) {

                wifi.setChecked(true);

            } else {

                wifi.setChecked(false);

            }
        }

    }
};

Wifi is a toggle button by the way.

Please help thanks!

1条回答
劫难
2楼-- · 2019-08-19 19:33

You need to set an intent filter associated with your receiver in your manifest.xml file like this :

<receiver android:name="<fully qualified name of your receiver class>" android:label="@string/label">
<intent-filter>
        <action android:name="package name + your action name" />
    </intent-filter>
</receiver>

then, in you activities, when you want to call your receiver, you just

sendBroadcast( new Intent( "package name + your action name" ) );

And then you should update your app, but within the ui thread to change a widget :

 final boolean checked = true;
 runOnUIThread( new Runnable() {
    public void run()
    { 
       wifi.setChecked( checked ):
    }
 });

But I guess you receiver is an inner class inside an acitivity (only way to get a reference on a widget). So, instead of registering your receiver through xml, you should register it through code.

Have a look at this thread.

Regards, Stéphane

查看更多
登录 后发表回答