我正在构建一个应用程序,该应用程序在启动时会检查设备是否已连接到互联网,如果未连接,则该应用程序将显示一个小吃店,告诉用户连接到互联网。另一方面,如果设备已连接到互联网,则该应用将转到其他布局。我希望我的应用在检测到设备已连接到互联网后检测互联网连接是否丢失。
此功能仅在启动应用程序后才有效,并且在启动后,如果连接断开,则应用程序将无法检测到它。 现在,我已将广播注册到清单文件,并且每当更改wifi状态时,应用程序都会停止运行。 你能帮忙吗?
这是WifiBroadcastReceiver:
public class WifiBroadcastReceiver extends BroadcastReceiver {
Context ctx;
public WifiBroadcastReceiver(){
super();
}
public WifiBroadcastReceiver(Context iCtx){
ctx = iCtx;
}
@Override
public void onReceive(Context context, Intent intent) {
NetworkInfo info = intent.getParcelableExtra((WifiManager.EXTRA_NETWORK_INFO));
if(info != null && info.isConnected()){
((Activity)context).setContentView(R.layout.activity_home);
ctx.unregisterReceiver(this);
}
这是主要活动:
public class MainActivity extends AppCompatActivity {
Snackbar wifiSnackbar = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WifiManager wifi = (WifiManager) getSystemService(this.WIFI_SERVICE);
if (!wifi.isWifiEnabled()) {
wifiSnackbar = Snackbar.make(findViewById(R.id.activity_main),
" not connected", Snackbar.LENGTH_INDEFINITE);
wifiSnackbar.setAction("Connect", new WifiButtonListener(this));
wifiSnackbar.show();
registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));
} else {
setContentView ( R.layout.activity_home );
registerReceiver(new WifiBroadcastReceiver(this), new IntentFilter("android.net.wifi.STATE_CHANGE"));
}
以下是WifiButtonListener:
public class WifiButtonListener implements View.OnClickListener {
Context ctx;
public WifiButtonListener(Context iCtx){
ctx = iCtx;
}
@Override
public void onClick(View view) {
WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
}
这是清单中注册接收者的代码:
<receiver android:name="WifiBroadcastReceiver" >
<intent-filter>
<action android:name="android.net.wifi.STATE_CHANGE" >
</action>
</intent-filter>
</receiver>