首頁 > web前端 > js教程 > 主體

使用 Web 工具進行 Android 開發:使用 Ionic React 進行生產的最快方式

WBOY
發布: 2024-08-07 20:53:13
原創
797 人瀏覽過

投資Android開發可以帶來龐大的設備市場佔有率、擴大的市場範圍和高投資報酬率。

全球擁有超過 68 億智慧型手機用戶。 Android 佔全球約 70% 的市場份額,相當於約 47.6 億用戶,找到您的利基市場觸手可及。這一切都是為了產生高品質、快速的應用程式。

Ionic 具有原生 Web 元件,使您能夠使用 HTML、JavaScript 和 CSS 等熟悉的工具實現高效能和高品質的 Android 應用程序,同時利用 Capacitor 來利用原生功能。

這不僅僅是一個關於 Ionic 的教學;它是關於建立高品質和高效能的 Android 應用程式以供生產使用。

本文是系列的簡介,其中我們將介紹以 React 作為前端的 Ionic 基礎知識,稍後使用 Capacitor 探索本機技術和 Web 技術之間的橋樑。

Ionic 框架:簡介

不同技術之間的運行時或橋樑並不是什麼新鮮事!

以 Node.js 為例。只有透過 Node,JavaScript 才能成為一種系統語言。

   [JS]
   [byte code]
   [Node] --> [N API] --> [C/C++ modules]
   [bindings]
   [Cpp][V8][libuv]
   [OS]

登入後複製

考慮使用 HTML、JavaScript 和 CSS 作為透過 Web 視圖的視圖的混合桌面應用程式。 Go Wails,一個非常高效能的桌面開發框架,就是基於這個想法。同樣,Rust Tauri 應用程式也遵循這一原則。

綁定已經在行動世界中存在並經過了一段時間的測試,例如 React Native 和 NativeScript。

開發界正在認識到的不僅是 UI 的重要性,還有美觀且響應靈敏的 UI 的重要性。該領域還沒有像 Web 技術一樣先進的框架。

Android 原生開發正在向 React 和 Kotlin 中可組合 UI 的方向轉變,遠離不太受青睞的 XML。

這個趨勢帶來了兩全其美的效果:原生速度和漂亮的可組合 UI。這就是 Ionic 在同類產品中脫穎而出的地方。不同之處在於 Ionic 很容易掌握——我在不到一個月的時間內成功建立了客戶的應用程式。

設定

建立一個新的專案資料夾並執行以下命令:

npx ionic start

登入後複製

這將引導您完成 Ionic 設定。選擇React作為本文的前端框架。

Ionic 仍然使用 Webpack 和 Create React App (CRA),因為 Vite 尚未支援 Ionic Web 元件的核心 Stencil.js。

一切安裝完畢後,在 VSCode 中開啟專案。我更喜歡刪除 npm 並使用 pnpm (此步驟是可選的)。如果你也想這樣做:

  • 刪除node_modules資料夾。

  • 刪除 package-lock.json 文件,而不是 package.json。

  • 執行 pnpm install。

要執行 Ionic 應用程序,請使用:

npx ionic serve

登入後複製

Ionic CLI 將處理一切。您也可以使用 --lab 選項進行類似手機的預覽(注意,這不是 Android 或 iOS 模擬器,而是「視圖」):

pnpm add -D @ionic/lab

npx ionic serve --lab

登入後複製

Android Dev with web Tools: fastest way to production with Ionic React

這使我們能夠預覽 UI 在類似手機的視圖上的外觀。

回顧結構

我假設您已在您選擇的 IDE 中開啟該專案。如果你沒有 React 經驗,這可能有點困難。我建議學習基本的 React 教學並學習 React 路由器。

入口點是index.tsx中的標準React應用程式渲染:

root.render(      

<React.StrictMode>

     <App/>

</React.StrictMode>

  );



登入後複製

在 App.tsx 中,它是一個路由器和選項卡導航欄,使用 Ionic 路由器和元件。 Ionic 元件是使用 Stencil.js 建立的原生 Web 元件,旨在看起來像行動應用程式。

Ionic 提供 CSS 檔案和主題來符合 iOS 和 Android 的標準。在 HTML 上使用 Ionic 元件以獲得自然的行動應用程式外觀和感覺。

讓我們從路由器開始分解 App.tsx。它的工作原理與 React Web 路由器類似,將路徑匹配到元件並在導航上渲染匹配的元件。



import Tab1 from './pages/Tab1';

import Tab2 from './pages/Tab2';

import Tab3 from './pages/Tab3';



    <IonRouterOutlet>
          <Route exact path="/tab1">
            <Tab1 />
          </Route>
          <Route exact path="/tab2">
            <Tab2 />
          </Route>
          <Route path="/tab3">
            <Tab3 />
          </Route>
          <Route exact path="/">
            <Redirect to="/tab1" />
          </Route>
     </IonRouterOutlet>

登入後複製

如果您熟悉後端,路徑就像一個端點,而元件是一個處理程序。

   <IonTabBar slot="bottom">
          <IonTabButton tab="tab1" href="/tab1">
            <IonIcon aria-hidden="true" icon={triangle} />
            <IonLabel>Tab 1</IonLabel>
          </IonTabButton>
          <IonTabButton tab="tab2" href="/tab2">
            <IonIcon aria-hidden="true" icon={ellipse} />
            <IonLabel>Tab 2</IonLabel>
          </IonTabButton>
          <IonTabButton tab="tab3" href="/tab3">
            <IonIcon aria-hidden="true" icon={square} />
            <IonLabel>Tab 3</IonLabel>
          </IonTabButton>
     </IonTabBar>



登入後複製

IonTabBar 在提供的插槽(在我們的應用程式的底部)處建立一個選項卡欄。神奇之處在於選項卡按鈕:使用 href 觸發路由器。所有正常的 React 程式碼,都包含在 Ionic 元件中。

關注其中一個標籤頁;它們本質上只是頁面。

   <IonPage>
      <IonHeader>
        <IonToolbar>
          <IonTitle>Tab 1</IonTitle>
        </IonToolbar>
      </IonHeader>
      <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Tab 1</IonTitle>
          </IonToolbar>
        </IonHeader>
        <ExploreContainer name="Tab 1 page" />
      </IonContent>
    </IonPage>



登入後複製

使用 Ionic 頁面元件可以開箱即用地處理諸如滾動和響應能力之類的事情。

Ionic 頁面的標準結構包括帶有工具列的標題和內容區域,與大多數行動應用程式類似。

標題:

  <IonHeader>
        <IonToolbar>
          <IonTitle>Tab 1</IonTitle>
        </IonToolbar>
      </IonHeader>

登入後複製

內容區:



    <IonContent fullscreen>
        <IonHeader collapse="condense">
          <IonToolbar>
            <IonTitle size="large">Tab 1</IonTitle>
          </IonToolbar>
        </IonHeader>
          <ExploreContainer name="Tab 1 page" />
      </IonContent>



登入後複製

The content area occupies most of the screen, where most of the application lives. The ExploreContainer acts as a slot; we can conditionally render components based on the name prop.

<ExploreContainer name="Tab 1 page" />

登入後複製

When name is "Tab 1," we render a component for that tab. You can hard code components for each tab, but the slot method is more flexible and composable.

For example, open the ExploreContainer component under the components folder and create three new components:

const Tab1Content = () => { return ( "I am tab 1 content" ); }

const Tab2Content = () => { return ( "I am tab 2 content" ); }

const Tab3Content = () => { return ( "I am tab 3 content" ); }

登入後複製

Now update the container to conditionally render based on the name prop:

<div className="container">
  {name.includes("Tab 1") ? <Tab1Content /> : name.includes("Tab 2") ? <Tab2Content /> : <Tab3Content />}
</div>


登入後複製

This is just an example; you can create an easy-to-follow pattern matching method. The updated preview should show "I am tab x content" based on the tab clicked.

This application is still web-based. We haven't installed or initialized Capacitor, which is responsible for turning our application into a native app.

Android Dev with web Tools: fastest way to production with Ionic React

Capacitor is a cross-platform native runtime for web apps, allowing us to create cross-platform iOS, Android, and Progressive Web Apps with JavaScript, HTML, and CSS.

Enabling Capacitor in Ionic

First, install Capacitor:

pnpm add @capacitor/core
pnpm add -D @capacitor/cli

登入後複製

Next, initialize the Capacitor configuration file:

npx cap init

登入後複製

The package ID should uniquely identify your app. We use an inverted domain name, e.g., com.example.app.

Capacitor is initialized. Run the following commands to install a Capacitor platform and primitive plugins:

pnpm add @capacitor/android



pnpm add @capacitor/app @capacitor/haptics @capacitor/keyboard @capacitor/status-bar


登入後複製

The following command will create the native android project structure and files in your ionic project:

npx cap add android

登入後複製

Important: Build the web app:

pnpm run build

登入後複製

to avoid this error before we run sync

[error] Could not find the web assets directory: .\build.

... More info: https://capacitorjs.com/docs/basics/workflow#sync-your-project

登入後複製

Once the build is finished, you can sync, copying the built web app; into the native webview:

npx cap sync

登入後複製

Believe it or not, we are ready to either build or preview the native application in an emulator.

We'll dive deeper into Capacitor and native development, environment setup, etc., in the next article.

Since we are still getting a feel for Ionic, let's play with a few Ionic components and wrap up with a simple application example.

PokeApp Example

You can easily find Ionic components in the documentation.

We'll implement a simple app that fetches Pokémon data from the PokeAPI, for a compact card view, and then build it into an APK.

Android Dev with web Tools: fastest way to production with Ionic React

From the results, we can already see how decent the app looks with no styling—thanks to the power of Ionic components.

Open the ExploreContainer component, and we'll work on Tab 2.

Update the component and add the following:

const BASE_LINK = "https://pokeapi.co/api/v2/pokemon/"



const Tab2Content = () => { 



 const [pokemon, setPokemon] = useState("pikachu")



 useEffect(()=> {    

if(pokemon != ""){    

  fetch(BASE_LINK + pokemon).then(async(poke)=> {

       console.log(await poke.json())              

    }).catch((err)=>console.log(err))   

 } 



 }, [pokemon])  



// add some padding to the div below

return  (

  <div style={{padding: ".5em"}}>

        I am tab 2 content  
 </div>

)}

登入後複製

We've added a state to track the Pokémon we want to look up, with the default being Pikachu:

const [pokemon, setPokemon] = useState("pikachu")

登入後複製

On load, we fetch the Pokémon data from the PokeAPI:

 useEffect(()=> {    

if(pokemon != ""){    

  fetch(BASE_LINK + pokemon).then(async(poke)=> {

       console.log(await poke.json())              

    }).catch((err)=>console.log(err))    } 

 }, [pokemon])  



登入後複製

Android Dev with web Tools: fastest way to production with Ionic React

The useEffect hook runs twice in React strict mode.

Instead of logging our result, let's turn it into a state so we can use it in our card component.

First, add a new useState under the Pokémon one:

 const [showResults, setResults] = useState()

登入後複製

Then, update the useEffect to set the results::



 useEffect(()=> {
    if(pokemon != ""){
      fetch(BASE_LINK + pokemon).then(async(poke)=> {


       const results = await poke.json()
       const {front_default} = results.sprites
       setResults({front_default})


      }).catch((err)=> console.log(err))
    }
  }, [pokemon])

登入後複製

The PokeAPI returns a lot of data. We are interested in the Pokémon image, specifically the front-facing image in the sprites object:

       const results = await poke.json()
       const {front_default} = results.sprites
       setResults({front_default})

登入後複製

If you are familiar with React, you know we have created the re-render on state change loop already. Now, we just need to consume the data:



 return  (
  <div style={{padding: ".5em"}}>
 <IonCard>
      <IonCardHeader>
        <IonCardTitle>{pokemon}</IonCardTitle>

      </IonCardHeader>

      <IonCardContent>
         <img src={showResults ? showResults.front_default : ""} />
      </IonCardContent>
    </IonCard>
  </div>
  )

登入後複製

We use an Ion card component to show the retrieved image:



   <IonCardContent>
         <img src={showResults ? showResults.front_default : ""} />
      </IonCardContent>



登入後複製

We have a basic structure already, but we can only show the default Pokémon. We need a way to accept user input (a Pokémon name) and make a fetch request based on that input.

The basic React approach is to have an input element bound to a useState value, updating it on onChange. However, in our case, this is problematic because every keystroke will trigger our useEffect, making multiple erroneous requests to the PokeAPI.

Instead, we need the user to type fully and press a search button to initiate the API call. Copy the code below and paste it on top of the Ion card:



 <IonItem>
        <IonInput aria-label="Pokemon" value={pokemon} ref={pokeNameref}></IonInput>
      </IonItem>
      <IonButton onClick={()=> PokeSearch() }>search</IonButton>

</IonItem>



登入後複製

From the code above, we need two things: a useRef pointing to our Ion input and a PokeSearch function triggered by an Ion button.

const Tab2Content = () => {
  const [pokemon, setPokemon] = useState("pikachu")
  const [showResults, setResults] = useState<any>()
  const pokeNameref = useRef<any>(null)

  const PokeSearch = () => {

    if(pokeNameref.current){

      console.log(pokeNameref.current.value)
         setPokemon(pokeNameref.current.value.toLocaleLowerCase())
    }
  }



....



}

登入後複製

The code below is responsible for updating the state, triggering the effect

 if(pokeNameref.current){

      console.log(pokeNameref.current.value)
         setPokemon(pokeNameref.current.value.toLocaleLowerCase())
    }



登入後複製

The entire component:

const Tab2Content = () => {
  const [pokemon, setPokemon] = useState("pikachu")
  const [showResults, setResults] = useState<any>()
  const pokeNameref = useRef<any>(null)

  const PokeSearch = () => {

    if(pokeNameref.current){

      console.log(pokeNameref.current.value)
      setPokemon(pokeNameref.current.value.toLocaleLowerCase())
    }
  }

  useEffect(()=> {
    if(pokemon != ""){
      fetch(BASE_LINK + pokemon).then(async(poke)=> {
       const results = await poke.json()
       console.log(results.sprites)
       const {front_default} = results.sprites
       setResults({front_default})
      }).catch((err)=> console.log(err))
    }
  }, [pokemon])

  return  (
  <div style={{padding: ".5em"}}>
      <IonItem>
        <IonInput aria-label="Pokemon" value={pokemon} ref={pokeNameref}></IonInput>
      </IonItem>
      <IonButton onClick={()=> PokeSearch() }>search</IonButton>
 <IonCard>
      <IonCardHeader>
        <IonCardTitle>{pokemon}</IonCardTitle>

      </IonCardHeader>

      <IonCardContent>
         <img src={showResults ? showResults.front_default : ""} />
      </IonCardContent>
    </IonCard>
  </div>
  )
}



登入後複製

Our simple PokeApp is complete. Make sure ionic serve --lab is running and type a few Pokémon names, such as:

bulbasaur dragonite

登入後複製

If everything is set up correctly, the Pokémon should change on search.

Not a life-changing application, but enough for learning Ionic. The next step requires Android Studio . Download it and follow the defaults while installing it.

PokeApp to APK

If you have never seen Android Studio, it’s probably the most complex IDE and has a steep learning curve!

I suggest following the defaults on installation and letting it run its course. My only suggestion is to select the option to install an emulator, which makes it easier to build and review the APK before bundling it.

When you download Android Studio for the first time, it'll download a lot of dependencies and set up Gradle, which may take some time. Let it do its thing. Gradle is a build tool for Android, similar to how we use Webpack or Vite in web development.

When you are ready and Android Studio is installed, navigate to our PokeApp in the terminal.

As an extra precaution, build and sync before opening the project in Android Studio to ensure there are no errors:

pnpm run build

npx cap sync

登入後複製

If the build is successful, we can rest assured there are no errors in our application. Next, open the project in Android Studio:

npx cap open android

登入後複製

Let the Gradle processes run:

Android Dev with web Tools: fastest way to production with Ionic React

When Gradle is done, try running the app in an emulator (top middle) in the IDE. If the app runs on the emulator, you can be sure it'll bundle to a standalone APK:

Android Dev with web Tools: fastest way to production with Ionic React

Check this extensive link for more ways to debug and run your APK: android studio run

Notes on Building the APK

There are a few steps involved in building an actual production APK for the Google Play Store, from setting up an Android console to creating banner images, which are tedious but essential tasks.

Note: The Android development account is a one-time fee. You can buy and set it up on Google Console.

Design, search keywords, and banners are beyond coding. This series is about getting the coding part right! I promise everything else will fall into place with practice and getting used to the tediousness of the Google Play Console.

In short, I will skip the Google Play Console for a few reasons:

  • It takes a while (2 weeks minimum) to get approved.
    When approved, the APK goes through a vetting process (takes time, may fail).

  • You can't submit an APK on Google Console unless you have banners and icons.

  • There is a lot of editing and icon generation for different screens.

These reasons make it impractical to include in a tutorial. But rest assured, what I will show you in this and upcoming articles will prepare you to build production-ready applications to publish in any store besides Google or for self-hosting.

However, if you already have a Google Play account, there are many articles and videos on publishing an Ionic Android app.

For our case, as long as we can generate a debug APK file and install it on an emulator or real phone, the other steps are just a Google search away!

Because this process is tedious, I will dedicate a separate article in this series to go through Android Studio, sign an APK, and build a release. For now, a debug APK will suffice as this article is already long.

Generating a debug apk

Look at your Android Studio top bar left; after the Android icon, there should be a hamburger menu button. Select to expand the menu. The build option is hidden there:

Android Dev with web Tools: fastest way to production with Ionic React

If the APK is generated successfully, a popup should show at the bottom right with a locate option, which will open the explorer to the APK path. You can share or install it on an Android device!

If you want to create a signed APK, the full production deal, Google has an extensive documentation

This was a high-level overview. We will go deeper with each article in the series.

在本文中,我們介紹了使用 Web 工具進行 Android 開發,我們選擇的框架是 Ionic。我們介紹了 Ionic 和 Ionic 元件的基礎知識、如何設定本機運行時橋 Capacitor,並建立了一個調試 APK。

如果您準備好深入了解 Capacitor,可以在這裡找到下一篇文章:Capacitor JS:Web 技術與原生 — Android、IOS、PWA 之間的橋樑

這只是開始。

如果您對更長、獨家、實用的內容感興趣,我有旨在提高您在 ko-fi 平台上的程式設計技能的等級和貼文。

以上是使用 Web 工具進行 Android 開發:使用 Ionic React 進行生產的最快方式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!