【发布时间】:2014-07-02 18:13:56
【问题描述】:
在我的OnCreate 方法中,我正在检查我的 Internet 连接。如果没有 Internet 连接,我将显示一个对话框,说明“用户没有 Internet”。现在打开 Internet 后,我希望再次调用 onCreate 并重新创建活动。
请注意:我是通过Android顶部栏的下拉菜单直接打开Wifi来开启互联网的。我怎样才能做到这一点?我是否应该创建一个广播接收器,因为在执行此操作时没有调用 OnResume 或 OnRestart。
请帮忙。
这是我的网络检查类
public class NetWorkCheck {
public NetWorkCheck(){
}
public static boolean hasConnection() {
ConnectivityManager cm = (ConnectivityManager) Getit.getContext().getSystemService(
Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null && wifiNetwork.isConnected()) {
return true;
}
NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null && mobileNetwork.isConnected()) {
return true;
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
return true;
}
return false;
}
}
这绝对是完美的。
在我的onCreate 中,我正在这样做
net = new NetWorkCheck();
if(net.hasConnection()){
Do task
}else{
Show dialog //I want this dialog to be vanished when user switched on the wifi.and activity should be re created
}
更新 2
目前,我正在使用一个广播接收器。
我在这样的对话框之后拨打电话:->
else{
new InternetNetworkHandle(SplashActivity.this).show();
registerReceiver(
new ConnectivityChangeReceiver(SplashActivity.class),
new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
广播接收器类
public class ConnectivityChangeReceiver
extends BroadcastReceiver {
String classname;
public ConnectivityChangeReceiver(String classname){
this.classname = classname;
}
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager conMan = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMan.getActiveNetworkInfo();
if (netInfo != null && netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
Log.d("WifiReceiver", "Have Wifi Connection");
act.finish();
Intent refresh = new Intent(context, ???); :-> Here how can i give my that activity name ? and i don't want hardcode.
startActivity(refresh);
}
else
Log.d("WifiReceiver", "Don't have Wifi Connection");
}
};
【问题讨论】:
-
你在标题中提到的 Toast 在哪里?
-
if(!net.hasConnection()){ 我正在展示 Toast }
-
请理解问题。我想在打开网络后重新创建活动。 !!有可能吗??
-
从APIv11开始可以调用
Activity.recreate(); -
如果我也使用 11.我应该在哪里写 Activity.recreate ??
标签: android android-activity oncreate