如何使用广播和接收器 [英] How to use broadcast and receivers
问题描述
我如何使用我的广播接收器?当我的应用程序启动我怎么做接收器不断地运行其code样?
How can I use my Broadcast receiver? Like when my app starts how do I make the receiver continually run its code?
我Reciver 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是由路的切换按钮。
Wifi is a toggle button by the way.
请帮助谢谢!
推荐答案
您需要设置您的接收器在manifest.xml文件这样的相关的意图过滤器:
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" ) );
然后你应该更新您的应用程序,但在UI线程内改变一个部件:
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 ):
}
});
但我猜你接收器是一种活性的研究(只有这样,才能得到一个小部件的引用)中的内部类。因此,而不是通过XML注册接收器,您应该通过code注册。
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.
看一看<一个href=\"http://stackoverflow.com/questions/4805269/programmatically-register-a-broadcast-receiver\">this螺纹。
问候,
斯特凡
Regards, Stéphane
这篇关于如何使用广播和接收器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!