現在越來越多的網站都擁有自己的App,這不僅能夠提高用戶的使用體驗,還能夠提高網站的曝光度和知名度。那么,如何將一個網站做成一個App呢?本文將分別介紹兩種實現方式。
一、基于Webview方式實現
Webview模式實現的原理是將網站的地址嵌入到應用程序中,然后直接使用WebView能力打開網址即可。需要注意的是,這種方式的APP比較機械、死板,UI效果不如原生。
1. 創建項目
打開Android Studio,點擊"Create New Project"選項,創建一個新的Android工程。
2. 引入webview
```
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:support-media-compat:28.0.0'
implementation 'com.android.support:cardview-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'
implementation 'com.bumptech.glide:glide:3.8.0'
implementation 'com.github.bumptech.glide:glide:3.7.0'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.firebase:firebase-core:16.0.6'
implementation 'com.google.firebase:firebase-messaging:17.3.4'
implementation 'com.google.firebase:firebase-crash:16.2.1'
implementation 'com.google.firebase:firebase-config:16.3.0'
implementation 'com.google.firebase:firebase-perf:16.2.4'
implementation 'com.google.code.gson:gson:2.8.2'
implementation 'com.squareup.okhttp3:okhttp:3.9.1'
implementation 'com.loopj.android:android-async-http:1.4.9'
implementation 'com.yalantis:ucrop:2.2.0-native'
implementation 'com.jakewharton:butterknife:7.0.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3' implementation 'com.tencent.tbs.tbssdk:sdk:43910'
}
```
3. 創建WebView控件
添加一個WebView,為其添加布局文件。
```
android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"/> ``` 4. 加載網頁到WebView中 通過添加以下代碼,可以將網站嵌入到APP中。 ``` webView = (WebView) findViewById(R.id.webView); webView.getSettings().setJavaScriptEnabled(true); webView.setWebViewClient(new WebViewClient(){ }); loadUrl("http://www.baike.com"); ``` 5. 運行測試 完成以上步驟后,點擊畫面上方"Run"按鈕即可測試,效果如下。  二、基于混合開發方式實現 基于混合開發方式的實現原理是:通過native封裝,實現對webview的管理,通過Javascript Interface的方式將native能力暴露給web頁面。通過這種方式,可以將網站轉化為原生界面,UI效果非常好,同時使用原生的組件,可以提高操作性能。 1. 安裝Cordova 首先需要在命令行窗口安裝Cordova,執行以下命令: ``` npm install -g cordova ``` 2. 創建項目 創建項目命令為: ``` cordova create myApp com.example.myapp myApp ``` 其中myApp為項目的名稱,com.example.myapp是包名,最后一個myApp表示工程名稱,命令執行之后在當前目錄下會生成一個myApp文件夾。 3. 添加平臺 執行以下命令,添加需要的平臺: ``` cordova platform add ios android ``` 4. 進入項目文件夾 進入myApp項目目錄中,執行以下命令: ``` cd myApp ``` 5. 編寫HTML代碼 在www目錄下編寫HTML代碼。HTML代碼會在webview中顯示,所有對Native進行調用的邏輯都在HTML代碼中實現。 6. 添加JavaScript代碼 該代碼需要放到HTML代碼中,用于調用Native方法。 ``` function callNative() { if (window.Native) { Native.show("hello world"); } } ``` 7. 添加native代碼 通過Java or Objective-C編寫Native代碼,可以通過該代碼實現一些Native能力。詳細實現方式可以根據需求來選擇,具體實現的方式可以參考React Native等其他框架的實現方式。 最后,打包發布即可。通過以上方法,就可以將網站做成App。如果需要獨立的應用市場,可以考慮通過打包工具生成安裝包發布到應用市場。