>

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에서는로드되지 않습니다. 이유가 무엇입니까?

  • 답변 # 1

    실제로 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

    에서 자세한 내용을 볼 수 있습니다. 와이즈 비즈

  • 답변 # 2

    이 방법은 Android 9에서도 모든 도메인에 적용됩니다. 다음과 같이 매니페스트에이 속성을 추가하십시오.

    Note: The guidance in this section applies only to apps that target Android 8.1 (API level 27) or lower. Starting with Android 9 (API level 28), cleartext support is disabled by default.

  • 답변 # 3

    보안 URL을 사용해보십시오. http 대신 https를 사용하십시오. Android 9.0은 보안되지 않은 URL을 허용하지 않습니다

    <application ... android:usesCleartextTraffic="true" ...> </application>

관련 자료

  • 이전 java - 다음 노래와 이전 노래를 재생하는 방법?
  • 다음 iOS in app purchase receipt validation - ios 인앱 구매 영수증 확인 - 서버가 다운되면 어떻게됩니까?