How to use broadcast and receivers

≡放荡痞女 提交于 2020-01-16 14:48:10

问题


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:


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



来源:https://stackoverflow.com/questions/6232600/how-to-use-broadcast-and-receivers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!