gpt4 book ai didi

java - 检测到网络连接时启动另一个 Activity

转载 作者:行者123 更新时间:2023-11-30 02:32:26 24 4
gpt4 key购买 nike

我目前正在做一个基于网络连接的项目。我正在开发一个定期检查网络连接的应用程序。如果没有连接,进度对话框应该旋转显示“无网络连接”,直到用户自己打开打开 wifi 或任何其他类型的互联网连接。打开 wifi 后,如果应用程序连接到 wifi,则进度对话框应关闭,控件应传递给另一个 Activity 。我已经在谷歌中搜索了很多次,但没有得到满意的答案。以下是我的代码:

     public class Alert extends Activity implements Runnable{


ProgressDialog pd;
WifiManager wm,wifiManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alert);


wm = (WifiManager) getSystemService(WIFI_SERVICE);

if(!wm.isWifiEnabled()) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");

Thread t = new Thread(this);
t.start();
}
}

@Override
protected void onResume() {

super.onResume();

if(wm.isWifiEnabled()) {
pd.dismiss();
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);

}
}

@Override
public void run() {
// TODO Auto-generated method stub

while(wm.getWifiState() != 3) {

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}
}
}

最佳答案

To check network connection, use ConnectivityManager class.
Add below method to your activity and call it to check network connection, if it returns true then it means network is available otherwise not.

private boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}

Now do it in your onCreate(...) method

if(!isNetworkAvailable(Alert.this)) {
pd = ProgressDialog.show(this, "Network Error!!", "Network not found.Please make sure there is presence of any kind of network connection!!");
Thread t = new Thread(this);
t.start();
}else{
if(pd != null && pd.isShowing()){
pd.dismiss();
}
Intent in=new Intent(Alert.this,WebPageView.class);
startActivity(in);
}

Hope this will help you.

关于java - 检测到网络连接时启动另一个 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27120183/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com