public abstract class MainActivity extends AppCompatActivity {
private static WebView web;
private WebView mWebView;
private java.lang.String url;
Boolean isInternetPresent = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = manager.getActiveNetworkInfo();
boolean hasConnect = (i != null && i.isConnected() && i.isAvailable());
if (hasConnect) {
} else {
}
Timer repeatTask = new Timer();
repeatTask.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
mWebView.loadUrl("http://www.smedk.ru/wp-content/uploads/files/education/rasp/1151.htm");
}
});
}
}, 0, 60000);
setContentView(R.layout.activity_main);
final ProgressDialog pd = ProgressDialog.show(MainActivity.this, "Загрузка расписания...", "Обновление данных...", true);
mWebView = (WebView) findViewById(R.id.web1);
mWebView.getSettings().setJavaScriptEnabled(true);
if (savedInstanceState == null) {
mWebView.loadUrl("http://www.smedk.ru/wp-content/uploads/files/education/rasp/1151.htm");
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
String newUA = "User Agent";
newUA = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/20100101 Firefox/4.0";
mWebView.getSettings().setUserAgentString(newUA);
mWebView.getSettings().setLoadWithOverviewMode(true);
mWebView.clearCache(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setDisplayZoomControls(false);
}
mWebView.setWebViewClient(new MyWebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Нет интернет подключения!");
alertDialog.setMessage("Пожайлуйста убедитесть включен ли " +
"Wi-Fi или мобильные данные и повторите попытку. ");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pd.show();
}
@Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
Toast.makeText(MainActivity.this, "Расписание загружено", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Обновление данных завершено", Toast.LENGTH_SHORT).show();
String webUrl = mWebView.getUrl();
}
});
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(
Environment.DIRECTORY_DOWNLOADS,
"image.png");
DownloadManager dm = (DownloadManager) getSystemService(
DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void TakeScreenshot() {
Picture picture = mWebView.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/Download/image.jpg");
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
} catch (Exception e) {
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.exit:
finish();
break;
case R.id.about:
Intent intent = new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
break;
case R.id.save:
Picture picture = mWebView.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
Toast.makeText(MainActivity.this, "Изображения сохранено в формате JPG", Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this, "Файл находится:" +
" /sdcard/image.jpg ", Toast.LENGTH_SHORT).show();
picture.draw(c);
FileOutputStream fos = null;
try {
fos = new FileOutputStream("mnt/sdcard/image.jpg");
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
}
} catch (Exception e) {
break;
}
return true;
}
return false;
}
}
import android.webkit.WebView; 导入android.webkit.WebViewClient;
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
@Override
public void onPageFinished(WebView view, String url) {
}
}
我创建了一个用于查看通话时间表的应用程序,通常决定在模拟器上测试我的应用程序。在旧版本上,webview可以正常工作,但是当我决定在android 9上进行测试时,我写了一个不可用的网页。
在旧版Android上,webView可以正常加载,但在Android 9上则无法加载。是什么原因?
答案 0 :(得分:13)
实际上,您应该避免使用http,但是如果没有办法,您可以这样做:
将@ xml / network_security_config添加到您的资源中:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
<domain includeSubdomains="true">www.smedk.ru</domain>
</domain-config>
</network-security-config>
将此安全配置添加到清单中,如下所示:
<application
...
android:networkSecurityConfig="@xml/network_security_config"
...>
...
</application>
现在,您允许在www.smedk.ru子域上使用HTTP连接。
您可以在https://developer.android.com/training/articles/security-config#CleartextTrafficPermitted
中阅读更多内容注意:本节中的指南仅适用于以Android 8.1(API级别27)或更低版本为目标的应用。从Android 9(API级别28)开始,默认情况下禁用明文支持。
答案 1 :(得分:8)
此方法也适用于Android 9的所有域。如下所示,将此属性添加到清单中:
<application
...
android:usesCleartextTraffic="true"
...>
</application>
答案 2 :(得分:3)
请尝试使用安全网址。 使用https而不是http。 Android 9.0不允许使用不安全的网址
答案 3 :(得分:0)
我的项目中发生了同样的问题,但以上所有答案均不适用于我。所以在这个问题上浪费了一整天之后,我得到的是
在Android版本8.1 / 9/10中,如果您在WebView中使用wrap_content属性作为高度,那么它将始终设置为0dp 。在早期版本(低于8.1)中,WebView中的wrap_content可以正常工作。但是从8.1及更高版本开始,您可以静态地设置高度,也可以使用setLayoutParameters()通过程序动态设置高度。还要在android清单中的Application(android:usesCleartextTraffic =“ true”)中添加额外的属性。
答案 4 :(得分:0)
// Step 1: in manifest :
<application
android:networkSecurityConfig="@xml/cleartextTrafficPermitted">
// Step 2:
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
// Step 3 Create drawable XML>>cleartextTrafficPermitted :
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<base-config cleartextTrafficPermitted="true">
<trust-anchors>
<certificates src="system" />
</trust-anchors>
</base-config>
</network-security-config>
答案 5 :(得分:0)
最后在android 10中,这对我来说可以加载全部内容,而不是部分内容。
webView.loadDataWithBaseURL(null, contentText, "text/html", "UTF-8", null);
答案 6 :(得分:0)
您可以使用Base64将HTML加载到WebView中。
String base64version = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
webView.loadData(base64version, "text/html; charset=UTF-8", "base64");