这是我第一次使用 AsyncTask 并且它可以工作,但是它很脏,因为我只是复制并粘贴了一些代码。我想以正确的方式并尽可能干净。那么任何人都可以帮助我清理我的代码并告诉我如何以正确的方式去做吗?你会帮我一个很大的忙,帮助我,让我在未来的 Android 开发中获得更多经验。我想从一开始就以正确的方式学习它;)
编辑: 在阅读了一堆教程并观看了视频之后,我认为我取得了巨大的进步!我很高兴我做到了!但是只剩下一个小问题了。在应用程序启动时,它不会加载页面。在我单击一个链接后,shouldOverrideUrlLoading 效果很好,但在启动时它只显示一个空白屏幕。有什么问题?
public class WebviewActivity extends MainActivity {
private WebView myWebView;
private ProgressDialog progressDialog;
private boolean mConnection = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ScrollView mainScrollView = (ScrollView)findViewById(R.id.ScrollView01);
myWebView = (WebView)findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
new checkConnection().execute();
if (mConnection == true){
view.loadUrl(url);
}
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
mainScrollView.fullScroll(ScrollView.FOCUS_UP);
}
});
myWebView.requestFocus(View.FOCUS_DOWN);
myWebView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_UP:
if (!v.hasFocus()) {
v.requestFocus();
}
break;
}
return false;
}
});
}
@Override
public void onResume() {
super.onResume();
new checkConnection().execute();
if (mConnection == true){
myWebView.loadUrl(webLink);
}
}
//------------------------------------------------------
//-----DOING THE CONNECTION CHECK IN ANOTHER THREAD-----
//------------------------------------------------------
public class checkConnection extends AsyncTask<Void, Void, Void>{
int mStatusCode = 0;
Exception mConnectionException;
@Override
protected void onPreExecute(){
super.onPreExecute();
progressDialog = ProgressDialog.show(WebviewActivity.this, "", "Loading...", true);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
try {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (cm.getActiveNetworkInfo().isConnectedOrConnecting()) {
URL url = new URL(webLink);
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
urlc.connect();
mStatusCode = urlc.getResponseCode();
if (mStatusCode == 200){
//Nothing to do.
}
}
} catch (IOException e) {
e.printStackTrace();
mConnectionException = e;
}
return null;
}
@Override
protected void onPostExecute(Void param){
progressDialog.dismiss();
if (mStatusCode == 200){
mConnection = true;
}
else if (mStatusCode == 404){
myWebView.loadUrl("file:///android_asset/errorpage404.html");
}
else {
myWebView.loadUrl("file:///android_asset/errorpage.html");
}
}
}
}