我正在使用webview
代码,在从一个页面转到另一个页面时显示处理循环。
代码非常有效,直到我们上传一些文件。文件uploaded
一旦用户重定向到另一个页面。此处理后,从一页显示到另一页的循环根本不显示。
我尝试使用谷歌搜索这个主题但没有用,看起来这是网络上的新问题大声笑。
还有关于javascript
alert box
的另一个问题。而不是给定标题,它显示"The page at http://example.com says:"
。在网上尝试过解决方案,但没有用......
如果有人可以在这里指出潜在的问题,将会非常有帮助。感谢...
以下是我的代码:
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.webkit.ConsoleMessage;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import static android.content.ContentValues.TAG;
public class MainActivity extends Activity {
public static WebView mWebview;
private android.content.Context Context;
private static String getIntentValue = null;
public static SharedPreferences sharedPreferences;
private ProgressDialog mProgressDialog;
private String mCM;
private ValueCallback<Uri> mUM;
private ValueCallback<Uri[]> mUMA;
private final static int FCR=1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
mWebview.setWebViewClient(new Callback());
if(Build.VERSION.SDK_INT >= 21){
Uri[] results = null;
//Check if response is positive
if(resultCode== Activity.RESULT_OK){
if(requestCode == FCR){
if(null == mUMA){
return;
}
if(intent == null){
//Capture Photo if no image available
if(mCM != null){
results = new Uri[]{Uri.parse(mCM)};
}
}else{
String dataString = intent.getDataString();
if(dataString != null){
results = new Uri[]{Uri.parse(dataString)};
}
}
}
}
mUMA.onReceiveValue(results);
mUMA = null;
}else{
if(requestCode == FCR){
if(null == mUM) return;
Uri result = intent == null || resultCode != RESULT_OK ? null : intent.getData();
mUM.onReceiveValue(result);
mUM = null;
}
}
}
private void enableHTML5AppCache() {
mWebview.getSettings().setDomStorageEnabled(true);
mWebview.getSettings().setAppCachePath("/data/data/" + getPackageName() + "/cache");
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Context = this;
String regId = FirebaseInstanceId.getInstance().getToken();
getIntentValue = getIntent().getStringExtra("value");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet Connection!", Toast.LENGTH_LONG).show();
// finish(); //Calling this method to close this activity when internet is not available.
} else {
mWebview = (WebView) findViewById(R.id.webview1);
WebSettings webSettings = mWebview.getSettings();
mWebview.getSettings().setJavaScriptEnabled(true);
mWebview.setWebChromeClient(new WebChromeClient());
mWebview.setWebChromeClient(new JsPopupWebViewChrome()); mWebview.setWebViewClient(new CustomWebViewClient());
//improve WebView Performance
mWebview.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
mWebview.getSettings().setAppCacheEnabled(true);
mWebview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
if(Build.VERSION.SDK_INT >= 21){
webSettings.setMixedContentMode(0);
mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT >= 19){
mWebview.setLayerType(View.LAYER_TYPE_HARDWARE, null);
}else if(Build.VERSION.SDK_INT < 19){
mWebview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
if(Build.VERSION.SDK_INT >=23 && (ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
}
mWebview.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setAllowFileAccess(true);
webSettings.setSavePassword(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
enableHTML5AppCache();
// progress dialog
mProgressDialog = new ProgressDialog(Context);
if (sharedPreferences.getBoolean("isKeyGenerated", true)) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com");
}
}
}
mWebview.setWebChromeClient(new WebChromeClient(){
//For Android 3.0+
public void openFileChooser(ValueCallback<Uri> uploadMsg){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FCR);
}
// For Android 3.0+, above method not supported in some android 3+ versions, in such case we use this
public void openFileChooser(ValueCallback uploadMsg, String acceptType){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(
Intent.createChooser(i, "File Browser"),
FCR);
}
//For Android 4.1+
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
mUM = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
MainActivity.this.startActivityForResult(Intent.createChooser(i, "File Chooser"), MainActivity.FCR);
}
//For Android 5.0+
public boolean onShowFileChooser(
WebView webView, ValueCallback<Uri[]> filePathCallback,
WebChromeClient.FileChooserParams fileChooserParams){
if(mUMA != null){
mUMA.onReceiveValue(null);
}
mUMA = filePathCallback;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if(takePictureIntent.resolveActivity(MainActivity.this.getPackageManager()) != null){
File photoFile = null;
try{
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCM);
}catch(IOException ex){
Log.e(TAG, "Image file creation failed", ex);
}
if(photoFile != null){
mCM = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
}else{
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("*/*");
Intent[] intentArray;
if(takePictureIntent != null){
intentArray = new Intent[]{takePictureIntent};
}else{
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, FCR);
return true;
}
});
}
private class JsPopupWebViewChrome extends WebChromeClient {
@Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
AlertDialog.Builder b = new AlertDialog.Builder(view.getContext())
.setTitle("ALERT!")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
b.show();
// Indicate that we're handling this manually
return true;
}
}
public class Callback extends WebViewClient{
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
Toast.makeText(getApplicationContext(), "Failed loading app!", Toast.LENGTH_SHORT).show();
}
}
// Create an image file
private File createImageFile() throws IOException {
@SuppressLint("SimpleDateFormat") String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "img_"+timeStamp+"_";
File storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return File.createTempFile(imageFileName,".jpg",storageDir);
}
// Function to load all URLs in same webview
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(Context)) {
if (url.contains("http://example.com")){ // Log.d("offline url", url);
view.loadUrl(url);
}else {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show(); // Log.d("other urls", url);
}
} else if (url.contains(".pdf")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
} else {
view.loadUrl(url);
}
return true;
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
//on page started, show loading page
mProgressDialog.setCancelable(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.show();
}
@Override
public void onPageFinished(WebView view, String url)
{
String currentPage= mWebview.getUrl();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("currentpage",currentPage);
editor.commit();
//after loading page, remove loading page
// TODO Auto-generated method stub
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) { // Log.e(TAG," Error occured while loading the web page at Url"+ failingUrl+"." +description); //
Intent intent = new Intent(MainActivity.this, noconnection.class);
intent.putExtra("a", "mainactivity is source");
startActivity(intent); //
Toast.makeText(getApplicationContext(), "Error occured, please check network connectivity", Toast.LENGTH_SHORT).show();
// super.onReceivedError(view, errorCode, description, failingUrl);
}
}
@Override
public void onBackPressed() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String currenturl = sharedPreferences.getString("currentpage", null);
mWebview.requestFocus();
if (!DetectConnection.checkInternetConnection(Context)) {
mWebview.loadUrl("http://example.com");
}else if (currenturl.contains("http://example.com")){
moveTaskToBack(true);
}else if(currenturl.contains("http://example.com")){
mWebview.loadUrl("http://example.com");
}else if(currenturl.contains("http://example.com")){ mWebview.loadUrl("http://example.com"); }else{
mWebview.goBack();
}
if (mWebview.canGoBack()) {
if (!DetectConnection.checkInternetConnection(Context)) {
Toast.makeText(Context, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
}
}
public static void loadUrl(String key) {
if (getIntentValue != null) {
mWebview.loadUrl("http://example.com");
getIntentValue = null;
} else {
mWebview.loadUrl("http://example.com");
}
}
public static void reLoad() {
mWebview.reload();
}
@Override
public void onConfigurationChanged(Configuration newConfig){
super.onConfigurationChanged(newConfig);
} }
答案 0 :(得分:0)
也许你应该覆盖WebChromeClient的onProgressChanged和控制对话框。