hello,又是我鑫鑫

————————–前言————————-

这吃给大家带来的博客是关于webview跳转第三方APP的

相信这个问题也为难过各位,那么话不多说,我直接上代码

—————————————————-

MainActivity.java

这里的活动名我没有改,使用的话,将所有的Contact_Customer改为MainActivity即可

package com.mycompany.myapp2;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mycompany.myapp2.R;

import java.io.FileNotFoundException;
import java.net.URISyntaxException;
import java.util.List;

public class Contact_Customer extends Activity {

    
//声明相应ID
	private WebView webView;
    
    private Context context;

    private TextView tvTitle;

    private TextView tvProgress;


//这里定义需要变量
    private ValueCallback<Uri&gt; uploadMessage;
    private ValueCallback<Uri[]&gt; uploadMessageAboveL;
    private final static int FILE_CHOOSER_RESULT_CODE = 10000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.Contact_Customer);//绑定页面ID
		getActionBar().hide();
		
		//去除导航栏
        Window navigation = getWindow();
        navigation.getDecorView().setSystemUiVisibility(
			View.SYSTEM_UI_FLAG_LAYOUT_STABLE
			| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
			| View.SYSTEM_UI_FLAG_LOW_PROFILE
			| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
			| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
			| View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
			| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        context= this;


		getActionBar().hide();//去除标题栏

      
        //获取标题显示进度显示布局ID
        final LinearLayout top = findViewById(R.id.top);
        //获得其他控件
        tvTitle = (TextView) findViewById(R.id.tv_title);
        // tvStart = (TextView) findViewById(R.id.tv_start);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        // tvEnd = (TextView) findViewById(R.id.tv_end);

        webView = (WebView) findViewById(R.id.Contact_Customer_web);//绑定网页布局ID


		WebSettings settings = webView.getSettings();//web一些设置
        settings.setJavaScriptEnabled(true);

		settings.setJavaScriptCanOpenWindowsAutomatically(true);
//         当网页需要保存数时据,设置下面属性
		settings.setDomStorageEnabled(true);

		//设置页面适应 窗口大小改变后页面适应改变
		settings.setUseWideViewPort(true);//设置使用webview推荐窗口,主要是为了配合下一个属性
		settings.setLoadWithOverviewMode(true);//设置网页自适应屏幕大小,该属性必须和上一属性配合使用

//        webSettings.setGeolocationEnabled(true); //启用还H5的地理定位服务
//         设置是否允许webview使用缩放功能
		settings.setSupportZoom(true);
		settings.setBuiltInZoomControls(true);
		settings.setDisplayZoomControls(false); //隐藏webview缩放按钮

		settings.setAllowFileAccess(true);//支持上传文件
//         提高网页渲染优先级
		settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不读取缓存
        // 加载指定网页
        
       // webView.loadUrl("https://qm.qq.com/cgi-bin/qm/qr?k=EWYf-_SRrmPF-f4xyYKQfNklEcHMsjVR&amp;noverify=0");
            //跳转QQ---项目中我安装一个APP,所以跳转成功
         webView.loadUrl("https://m.jumpwx.com/wx/?i=170");
             //跳转微信---项目中我并没有安装这个,所以他会提示无法跳转。
        
        

        webView.setWebViewClient(new WebViewClient(){
            //跳转第三应用
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    
                    try {
                         if (!(url.startsWith("http") || url.startsWith("https"))) {
                        Intent intent = new Intent();
                        intent.setAction(Intent.ACTION_VIEW);
                        intent.setData(Uri.parse(url));
                        startActivity(intent);
                        return true;
                    }
                        view.loadUrl(url);
                        return true;
                    } catch (Exception e) {
                        // 防止没有安装的情况
                        e.printStackTrace();
                        Toast.makeText(Contact_Customer.this,"您所打开第三方App未安装!",Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
                
                    
                
                
               
            });
            
      

        webView.setWebChromeClient(new WebChromeClient() {

            //文件上传
            
				// For Android < 3.0
				public void openFileChooser(ValueCallback<Uri> valueCallback) {
					uploadMessage = valueCallback;
					openImageChooserActivity();
				}

				// For Android  >= 3.0
				public void openFileChooser(ValueCallback valueCallback, String acceptType) {
					uploadMessage = valueCallback;
					openImageChooserActivity();
				}

				//For Android  >= 4.1
				public void openFileChooser(ValueCallback<Uri> valueCallback, String acceptType, String capture) {
					uploadMessage = valueCallback;
					openImageChooserActivity();
				}

				// For Android >= 5.0
				@Override
				public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams) {
					uploadMessageAboveL = filePathCallback;
					openImageChooserActivity();
					return true;
				}


                
    
                //获取网站标题
                @Override
                public void onReceivedTitle(WebView view, String title) {
                    tvTitle.setText(title);
                }
                //进度显示
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    if (newProgress < 100) {
                        tvProgress.setText(newProgress + "%");
                    } else {
                        tvProgress.setText("100%");
                        top.setVisibility(View.GONE);
                    }
                }
     
    
                
        
                
			});







		//设置下载监听
        webView.setDownloadListener(new DownloadListener() {



				@Override
				public void onDownloadStart(final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {

					new AlertDialog.Builder(Contact_Customer.this)
						.setTitle("信息提示")//设置对话框标题
						.setIcon(R.drawable.ic_launcher)
						.setMessage("下载将跳转浏览器是否选择?")
						.setPositiveButton("是", new DialogInterface.OnClickListener() {//添加确定按钮

							@Override
							public void onClick(DialogInterface dialog, int which) {//确定按钮响应事件

								Uri uri = Uri.parse(url);
								Intent intent = new Intent(Intent.ACTION_VIEW, uri);
								startActivity(intent);
							}
						}).setNegativeButton("否", new DialogInterface.OnClickListener() {//添加返回按钮

							@Override
							public void onClick(DialogInterface dialog, int which) {//响应事件

							}

						}).show();//在按键响应事件中显示对话框
				}
			});

			
/*
		// 长按点击事件
		webView.setOnLongClickListener(new View.OnLongClickListener() {
				@Override
				public boolean onLongClick(View view) {
					final WebView.HitTestResult hitTestResult = webView.getHitTestResult();
					// 如果是图片类型或者是带有图片链接类型
					if(hitTestResult.getType()== WebView.HitTestResult.IMAGE_TYPE||
					   hitTestResult.getType()== WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE){
						// 弹出保存图片对话框
						AlertDialog.Builder builder = new AlertDialog.Builder(context);
						builder.setTitle("提示");
						builder.setMessage("保存图片到本地");
						builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialogInterface, int i) {
									String url = hitTestResult.getExtra();
									// 下载图片到本地
									DownPicUtil.downPic(url, new DownPicUtil.DownFinishListener(){

											@Override
											public void getDownPath(String s) {
												Toast.makeText(context,"下载完成",Toast.LENGTH_LONG).show();
												Message msg = Message.obtain();
												msg.obj=s;
												handler.sendMessage(msg);
											}
										});

								}
							});
						builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
								// 自动dismiss
								@Override
								public void onClick(DialogInterface dialogInterface, int i) {
								}
							});
						AlertDialog dialog = builder.create();
						dialog.show();
					}
					return true;
				}
			});
*/
    }




    /*文件上传*/
  
    //这里定义具体上传函数
    private void openImageChooserActivity() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "选择文件"), FILE_CHOOSER_RESULT_CODE);

	}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILE_CHOOSER_RESULT_CODE) {
            if (null == uploadMessage && null == uploadMessageAboveL) return;
            Uri result = data == null || resultCode != RESULT_OK ? null : data.getData();
            if (uploadMessageAboveL != null) {
                onActivityResultAboveL(requestCode, resultCode, data);
            } else if (uploadMessage != null) {
                uploadMessage.onReceiveValue(result);
                uploadMessage = null;
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void onActivityResultAboveL(int requestCode, int resultCode, Intent intent) {
        if (requestCode != FILE_CHOOSER_RESULT_CODE || uploadMessageAboveL == null)
            return;
        Uri[] results = null;
        if (resultCode == Activity.RESULT_OK) {
            if (intent != null) {
                String dataString = intent.getDataString();
                ClipData clipData = intent.getClipData();
                if (clipData != null) {
                    results = new Uri[clipData.getItemCount()];
                    for (int i = 0; i < clipData.getItemCount(); i++) {
                        ClipData.Item item = clipData.getItemAt(i);
                        results[i] = item.getUri();
                    }
                }
                if (dataString != null)
                    results = new Uri[]{Uri.parse(dataString)};
            }
        }
        uploadMessageAboveL.onReceiveValue(results);
        uploadMessageAboveL = null;


    }


        /*图片文件的下载*/

    Handler handler =new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String picFile = (String) msg.obj;
            String[] split = picFile.split("/");
            String fileName = split[split.length-1];
            try {
                MediaStore.Images.Media.insertImage(getApplicationContext().getContentResolver(), picFile, fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            // 最后通知图库更新
            getApplicationContext().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + picFile)));
			//MyToast("图片保存图库成功", 1100);
		}
    };

    
    
    /*自定义Toast*/

    //具体见我自定义Toast的文章,这你就不写进去了
  /*  
	public void MyToast(String str, int showTime) {
        View view= LayoutInflater.from(this).inflate(R.layout.view_toast_custom,null);
        TextView tv_msg = (TextView) view.findViewById(R.id.tvToast);
        tv_msg.setText(str);
        Toast toast = new Toast(this);
        toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 20);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(view);
        toast.show();

    }*/


    /*返回键的监听*/
    // 监听返回返回网页的上一层
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
            if(webView != null){
                webView.goBack();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }




}

———————–说明————-———–

上面这个activity是跳转至微信小程序,而我并没有安装微信,所以他不提示以下的效果

———————————————————

如果换成安装了的APP,比如果:QQ

像我不仅有QQ还有TIM,所以他会弹出以下效果

———————————————————

话不多说,继续上activity_main.xml

—————————————————–

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_height="match_parent"
	android:layout_width="match_parent"
	android:orientation="vertical"
	android:background="#FFFFFFFF">

	<LinearLayout
		android:id="@+id/top"
		android:layout_width="match_parent"
		android:layout_height="95dp"
		android:orientation="vertical"
		android:layout_marginTop="15dp"
		android:layout_weight="1.0"
		android:layout_marginBottom="3dp">

		<TextView
			android:id="@+id/tv_title"
			android:layout_width="match_parent"
			android:layout_height="wrap_content"
			android:text="获取标题"
			android:gravity="center"
			android:textStyle="bold"
			android:textColor="#FF000000"/>

		<LinearLayout
			android:layout_height="wrap_content"
			android:layout_width="match_parent">

			<TextView
				android:id="@+id/tv_progress"
				android:layout_width="match_parent"
				android:layout_height="wrap_content"
				android:text="获取加载进度"
				android:layout_weight="1.0"
				android:textStyle="bold"
				android:textColor="#FF000000"
				android:gravity="center"/>

		</LinearLayout>

	</LinearLayout>

	<LinearLayout
		android:layout_height="match_parent"
		android:layout_width="match_parent"
		android:orientation="vertical"
		android:layout_weight="1.0">

		<WebView
			android:id="@+id/Contact_Customer_web"
			android:layout_width="match_parent"
			android:layout_height="match_parent"/>

	</LinearLayout>

</LinearLayout>

———————————————————

从MainActivity一样,将所有的Contact_Customer改为MainActivity,或者在JAVA代码中你不要改webview的id,否则就要与xmlwebview的ID样,不然会闪退

———————————————————

基本也就是这样的,就到这里了吧。再见~

有任何问题评论区问我哦~

原文地址:https://blog.csdn.net/qq_48944757/article/details/125244097

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_11241.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注