Android6.0 WebView显示空白页面
问题描述:
我试图用webView加载一个页面,它只是在我的手机上显示一个空白页面。这里是代码和类。
的AndroidManifest.xmlAndroid6.0 WebView显示空白页面
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bobqiu.http_01" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >
<activity android:name=".MainActivity"
android:hardwareAccelerated="false">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET"/>
activity_main.xml中
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="com.example.bobqiu.http_01.MainActivity">
<WebView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/webview1"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="72dp" />
</RelativeLayout>
HttpThread.java
package com.example.bobqiu.http_01;
import android.os.Handler;
import android.webkit.WebView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* Created by Bobqiu on 2016/9/22.
*/
public class HttpThread extends Thread {
private String url;
private WebView webView;
private Handler handler;
public HttpThread(String url,WebView webView,Handler handler){
this.url = url;
this.webView = webView;
this.handler = handler;
}
public void run(){
try {
URL httpUrl = new URL(url);
try {
HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
final StringBuffer sb = new StringBuffer();
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String str;
while((str = reader.readLine())!=null){
sb.append(str);
}
handler.post(new Runnable() {
@Override
public void run() {
webView.loadData(sb.toString(),"text/html;
charset=utf-8",null);
}
});
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
MainActivity.java
package com.example.bobqiu.http_01;
import android.Manifest;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView= (WebView) this.findViewById(R.id.webview1);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
int permissionCheckContextCompat.
checkSelfPermission(MainActivity.this,
Manifest.permission.INTERNET);
System.out.println("!!!!!"+permissionCheck);//it shows 0 in console
new HttpThread("https://m.baidu.com/",webView,handler).start();
}
}
我也尝试了webView.loadDataWithBaseURL方法,仍然不起作用... 请帮助我,谢谢!
答
尝试加载的数据是这样的:
webView.loadData(sb.toString(),"text/html",UTF-8);
或本:
webView.loadDataWithBaseURL("",sb.toString(),"text/html",UTF-8,"");
答
添加上网权限在你的清单。没有它,你的应用程序将无法访问互联网服务。
<manifest xlmns:android...>
...
<uses-permission android:name="android.permission.INTERNET" />
<application ...
</manifest>
编辑 -
在安卓米及以上,你必须在运行时从用户询问权限。
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.INTERNET)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (shouldShowRequestPermissionRationale(
Manifest.permission.INTERNET)) {
// Explain to the user why we need to read the contacts
}
requestPermissions(new String[]{Manifest.permission.INTERNET},
1);
// MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE is an
// app-defined int constant
return;
}else {
new HttpThread("https://m.baidu.com/",webView,handler).start();
}
}else {
new HttpThread("https://m.baidu.com/",webView,handler).start();
}
并重写此方法 - - 调用
new HttpThread("https://m.baidu.com/",webView,handler).start();
运行该代码授予权限之前
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case 1: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
new HttpThread("https://m.baidu.com/",webView,handler).start();
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Snackbar.make(parent, "Click on allow to Access Internet in you application", Snackbar.LENGTH_LONG)
.setAction("CLOSE", new View.OnClickListener() {
@Override
public void onClick(View view) {
}
})
.setActionTextColor(getResources().getColor(android.R.color.holo_purple
)).show();
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
此之后,它应该在你的版本的Android M手机运行了。希望它有效。
+0
对不起,我已经添加了它,但它不工作...我想知道如果它是Android系统的版本,它可以在模拟器(Android 4.4.2)上正常工作,但不适用于真正的手机(Android 6.0),无论如何thx! – BobHU
我想你的意思是webView.loadUrl(Strng url)...我试过了,它效果很好。谢谢。但我仍然想直接理解loadByte和loadUrl之间的区别。此外上面的代码在模拟器(Android 4.4中工作得很好。2),但未能显示在我的真实手机(Android 6.0)中。这两个版本有什么区别吗?如果是关于Android 6.0中的运行时检查,我已检查并且结果为0,这意味着它是允许的。 – BobHU
@BOBHU我编辑了我的答案。看一看。 –