我有2个活动 MainActivity 和 ErrorActivity 。
当用户没有连接时,我要将其从 MainActivity 重定向到 ErrorActivity 。
这是我的 MainActivity 文件:
package com.xcoder.onestep;
public class MainActivity extends AppCompatActivity {
private WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setAllowContentAccess(true);
webSettings.setAllowFileAccess(true);
webView.setWebViewClient(new WebViewClient() {
public void onRecievedError(WebView view, int errorCode, String description, String faillingUrl) {
}
});
}
}
@Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
当没有连接将用户重定向到 ErrorActivity.class
时,我想不带按钮使用它答案 0 :(得分:0)
public boolean haveNetworkConnection(Context context) {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
使用Above Function并在oncreate中进行检查
if(!haveNetworkConnection(this)){
startActivity(new Intent(this,ErrorActivity.Class));
}