1. 程式人生 > >安卓開發騰訊X5第三庫使用心得

安卓開發騰訊X5第三庫使用心得

2:新建jniLibs目錄
這裡寫圖片描述

3:最後在APP的build.gradle檔案下新增幾行程式碼

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.guet.andream.andreamtwo"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
versionName "1.0" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" ndk { abiFilters "armeabi", "armeabi-v7a", "x86", "mips" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'
), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { exclude group: 'com.android.support', module: 'support-annotations' }) compile 'com.android.support:appcompat-v7:25.3.1'
testCompile 'junit:junit:4.12' compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7' compile 'com.github.ybq:Android-SpinKit:1.1.0' }

4:在APP啟動時進行初始化

public class App extends Application {@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    //蒐集本地tbs核心資訊並上報伺服器,伺服器返回結果決定使用哪個核心。

    QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

        @Override
        public void onViewInitFinished(boolean arg0) {
            // TODO Auto-generated method stub
            //x5核心初始化完成的回撥,為true表示x5核心載入成功,否則表示x5核心載入失敗,會自動切換到系統核心。
            Log.d("app", " onViewInitFinished is " + arg0);
        }

        @Override
        public void onCoreInitFinished() {
            // TODO Auto-generated method stub
        }
    };
    //x5核心初始化介面
    QbSdk.initX5Environment(getApplicationContext(),  cb);
}
}

這樣就配置完了

後面就可以進行開發了,話不多說直線上程式碼
程式碼部分,首先是佈局檔案

<?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"
    tools:context="com.guet.andream.andreamtwo.MainActivity">
   <com.guet.andream.andreamtwo.X5WebView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/web_filechooser">
   </com.guet.andream.andreamtwo.X5WebView>
   <com.github.ybq.android.spinkit.SpinKitView
       xmlns:app="http://schemas.android.com/apk/res-auto"
       android:id="@+id/spin_kit"
       style="@style/SpinKitView.Large.Circle"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_gravity="center"
       android:layout_centerVertical="true"
       android:layout_centerHorizontal="true"
       app:SpinKit_Color="@color/colorAccent" />
   <TextView
       android:layout_width="wrap_content"
       android:text="載入中...."
       android:id="@+id/loadText"
       android:textColor="@color/colorAccent"
       android:textSize="18sp"
       android:layout_below="@+id/spin_kit"
       android:layout_centerHorizontal="true"
       android:layout_height="wrap_content" />
   <View
       android:layout_width="match_parent"
       android:layout_height="25dp"
       android:background="#fff"
       android:id="@+id/hiddenView"
       android:layout_alignParentBottom="true"
      />
</RelativeLayout>

接下來的是自定義webview

public class X5WebView extends WebView {
    private WebViewClient client = new WebViewClient() {
        /**
         * 防止載入網頁時調起系統瀏覽器
         */
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    };

    @SuppressLint("SetJavaScriptEnabled")
    public X5WebView(Context arg0, AttributeSet arg1) {
        super(arg0, arg1);
        this.setWebViewClient(client);
        initWebViewSettings();
        this.getView().setClickable(true);
    }

    private void initWebViewSettings() {
        WebSettings webSetting = this.getSettings();
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(true);
        // webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        // webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        // webSetting.setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);

        // this.getSettingsExtension().setPageCacheCapacity(IX5WebSettings.DEFAULT_CACHE_CAPACITY);//extension
        // settings 的設計
    }

    public X5WebView(Context arg0) {
        super(arg0);
        setBackgroundColor(85621);
    }

}

接下來的是activity的程式碼

public class MainActivity extends AppCompatActivity {
    private X5WebView webView;
    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;
    private ProgressBar progressBar;
    private View hiddenView;
    private TextView loadText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (X5WebView) findViewById(R.id.web_filechooser);
         progressBar = (ProgressBar)findViewById(R.id.spin_kit);
        hiddenView=findViewById(R.id.hiddenView);
        loadText= (TextView) findViewById(R.id.loadText);
//配置載入動畫
        FadingCircle doubleBounce = new FadingCircle();
        progressBar.setIndeterminateDrawable(doubleBounce);


        webView.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.e("test", "openFileChooser 3");
                MainActivity.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.e("test", "openFileChooser 4:" + filePathCallback.toString());
                MainActivity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }

        });
        webView.getSettings().setUseWideViewPort(true); //自適應螢幕
        webView.loadUrl("https://jianfengandream.kuaizhan.com/");

        //webView載入監聽
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);

                progressBar.setVisibility(View.GONE);
                hiddenView.setVisibility(View.GONE);
                loadText.setVisibility(View.GONE);
            }

            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                super.onPageStarted(webView, s, bitmap);
            }
        });
        //webView載入百分比監聽
        webView.setWebChromeClient(new WebChromeClient()
        {
            @Override
            public void onProgressChanged(WebView webView, int i) {
                super.onProgressChanged(webView, i);
                Log.e("---TEST---", String.valueOf(i));


            }
        });

    }
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
            webView.goBack(); // goBack()表示返回WebView的上一頁面
            return true;
        }
        else {
            finish();
            return true;
        }
    }
    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }

    /**
     * 確保登出配置能夠被釋放
     */
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        if (this.webView != null) {
            webView.destroy();
        }
        super.onDestroy();
    }
}

最後是效果圖
這裡寫圖片描述