我是android的初学者。我只是想知道什么是广播接收器(如果可能的话有一个例子),它在onReceive()方法上。以及我们如何使用该接收器检查互联网连接。
那么我应该使用相同的方法来检查Internet连接,还是只在Main类中创建一个静态方法并在其他类中访问它?
答案 0 :(得分:2)
好的,所以我不是最好的程序员,但这应该有用。
这是一个片段,但您应该可以轻松地将其更改为 活性。
首先制作3个变量:
Context _mContext;
BroadcastReceiver br = null;
IntentFilter filter;
你的onCreate()中的粘贴了这个:
BroadcastReceiver br = new MyBroadCastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
_mContext = getActivity().getApplicationContext()
_mContext.registerReceiver(br, filter);
将此片段注册到broadcastreceiver类MyBroadCastReceiver。
现在制作一个MyBroadCastReceiver类并粘贴它:
public class MyBroadCastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int extraWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
switch(extraWifiState) {
case: WifiManager.WIFI_STATE_DISABLED:
//do something
break;
case WifiManager.WIFI_STATE_ENABLED:
//do something
break;
case: WifiManager.WIFI_STATE_ENABLING:
//do something
break;
case: WifiManager.WIFI_STATE_DISABLING:
//do something
break;
case: WifiManager.WIFI_STATE_UNKNOWN:
//do something with data if you desire so, I found it unreliable until now so i've done nothing with it
}
}
}`
回到你的片段并将其粘贴在底部的某处:
@Override
public void onPause() {
try {
if (br == null) {
Log.d("Receiver", "Can't unregister a receiver which was never registered");
} else {
getActivity().getApplicationContext().unregisterReceiver(br);
br = null;
}
} catch(Exception err) {
Log.e(err.getClass().getName(), err.getMessage(), err);
Log.e("Receiver not registered", "Couldn't get context");
}
super.onPause();
}
@Override
public void onResume() {
if(br != null) {
Log.d("Receiver", "Can't register receiver which already has been registered");
} else {
try {
br = new MyBroadCastReceiver();
filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(CONNECTIVITY_SERVICE);
_mContext = getActivity().getApplicationContext();
_mContext.registerReceiver(br, filter);
} catch(Exception err) {
Log.e(err.getClass().getName(), err.getMessage(), err);
}
}
super.onResume();
}
您应该可以在任何地方呼叫注册/取消注册广播。 我希望这已经足够了
答案 1 :(得分:0)
<receiver
android:name=".InternetConnectorBroadcastReceiver"
android:enabled="true">
<intent-filter>
<!-- Intent filters for broadcast receiver -->
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
public class InternetConnectionBroadcastReceiver extends BroadcastReceiver {
public InternetConnectorBroadcastReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
}
}