Rumah > hujung hadapan web > tutorial js > Android Dev dengan Alat web: cara terpantas untuk menghasilkan dengan Ionic React

Android Dev dengan Alat web: cara terpantas untuk menghasilkan dengan Ionic React

WBOY
Lepaskan: 2024-08-07 20:53:13
asal
823 orang telah melayarinya

Melabur dalam pembangunan Android boleh menghasilkan bahagian pasaran peranti yang besar, jangkauan pasaran yang diperluas dan pulangan pelaburan yang tinggi.

Dengan lebih 6.8 bilion pengguna telefon pintar di seluruh dunia. Android memegang kira-kira 70% bahagian pasaran global, diterjemahkan kepada kira-kira 4.76 bilion pengguna, mendapati niche anda boleh dicapai. Ini semua tentang menghasilkan aplikasi yang berkualiti tinggi dan pantas.

Ionic, dengan komponen web asli, membolehkan anda mencapai apl Android yang berprestasi dan berkualiti tinggi menggunakan alatan biasa seperti HTML, JavaScript dan CSS, sambil memanfaatkan fungsi asli dengan Capacitor.

Ini lebih daripada sekadar tutorial tentang Ionic; ia mengenai membina aplikasi Android yang berkualiti dan berprestasi sedia untuk pengeluaran.

Artikel ini ialah pengenalan kepada siri di mana kami akan membincangkan asas Ionic dengan React sebagai bahagian hadapan kami dan kemudian meneroka jambatan antara teknologi asli dan web menggunakan Capacitor.

Rangka kerja ionik: Satu Pengenalan

Waktu tayangan atau jambatan antara teknologi yang berbeza bukanlah perkara baharu!

Ambil Node.js, sebagai contoh. Hanya melalui Node JavaScript boleh menjadi bahasa sistem.

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

Salin selepas log masuk

Pertimbangkan aplikasi desktop hibrid menggunakan HTML, JavaScript dan CSS sebagai paparan melalui paparan web. Go Wails, rangka kerja pembangunan desktop yang sangat berprestasi, adalah berdasarkan idea ini. Begitu juga, aplikasi Rust Tauri beroperasi berdasarkan prinsip ini.

Pengikatan telah wujud dan telah diuji untuk seketika dalam dunia mudah alih, dengan contoh seperti React Native dan NativeScript.

Dunia pembangunan menyedari kepentingan bukan sahaja UI tetapi UI yang cantik dan responsif. Tiada rangka kerja semaju teknologi web dalam bidang ini.

Pembangunan asli Android sedang beralih ke arah React dengan UI boleh gubah dalam Kotlin, beralih daripada XML yang kurang digemari.

Arah aliran ini membawakan yang terbaik dari kedua-dua dunia: kelajuan asli dengan UI boleh gubah yang cantik. Di situlah Ionic menonjol di kalangan rakan sebayanya. Perbezaannya ialah Ionic mudah difahami—saya berjaya membina aplikasi pelanggan dalam masa kurang dari sebulan.

Persediaan

Buat folder projek baharu dan jalankan yang berikut:

npx ionic start

Salin selepas log masuk

Ini akan membawa anda melalui persediaan Ionik. Pilih React sebagai rangka kerja bahagian hadapan untuk artikel ini.

Ionic masih menggunakan Webpack dan Create React App (CRA) kerana Vite belum lagi menyokong Stencil.js, teras komponen web Ionic.

Setelah semuanya dipasang, buka projek dalam VSCode. Saya lebih suka mengalih keluar npm dan menggunakan pnpm (langkah ini adalah pilihan). Jika anda ingin melakukan perkara yang sama:

  • Padamkan folder node_modules.

  • Padamkan fail package-lock.json, bukan package.json.

  • Jalankan pemasangan pnpm.

Untuk menjalankan aplikasi Ionik, gunakan:

npx ionic serve

Salin selepas log masuk

Ionic CLI akan menguruskan segala-galanya. Anda juga boleh menggunakan pilihan --lab untuk pratonton seperti telefon (nota, ini bukan emulator Android atau iOS, tetapi "paparan"):

pnpm add -D @ionic/lab

npx ionic serve --lab

Salin selepas log masuk

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

Ini membolehkan kami melihat pratonton rupa UI pada paparan seperti telefon.

Merentas struktur

Saya menganggap anda telah membuka projek dalam IDE pilihan anda. Jika anda tidak mempunyai pengalaman React, ini mungkin agak mencabar. Saya cadangkan mengambil tutorial React asas dan mempelajari tentang penghala React.

Titik masuk ialah paparan aplikasi React standard dalam index.tsx:

root.render(      

<React.StrictMode>

     <App/>

</React.StrictMode>

  );



Salin selepas log masuk

Dalam App.tsx, ia adalah penghala dan bar navigasi tab, menggunakan penghala dan komponen ionik. Komponen ionik ialah komponen web asli yang dibina dengan Stencil.js, direka bentuk untuk kelihatan seperti aplikasi mudah alih.

Ionic menyediakan fail CSS dan tema untuk dipadankan dengan piawaian kedua-dua iOS dan Android. Gunakan komponen ionik ke atas HTML untuk rupa dan rasa aplikasi mudah alih semula jadi.

Mari kita pecahkan App.tsx, bermula dengan penghala. Ia berfungsi sama seperti penghala web React, memadankan laluan ke komponen dan memaparkan komponen yang sepadan pada navigasi.



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>

Salin selepas log masuk

Jika anda biasa dengan bahagian belakang, laluan itu seperti titik akhir dan komponennya ialah pengendali.

   <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>



Salin selepas log masuk

IonTabBar mencipta bar tab pada slot yang disediakan, dalam aplikasi kami bahagian bawahnya. Keajaiban ada dalam butang tab: mencetuskan penghala menggunakan href. Semua kod React biasa, dibalut dengan komponen Ionik.

Ikuti salah satu halaman tab; ia pada asasnya hanya halaman.

   <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>



Salin selepas log masuk

Menggunakan komponen halaman Ionik mengendalikan perkara seperti menatal dan responsif di luar kotak.

Struktur standard halaman Ionik termasuk pengepala dengan bar alat dan kawasan kandungan, serupa dengan kebanyakan aplikasi mudah alih.

Tajuk:

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

Salin selepas log masuk

Kawasan kandungan:



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



Salin selepas log masuk

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" />

Salin selepas log masuk

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" ); }

Salin selepas log masuk

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>


Salin selepas log masuk

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

Salin selepas log masuk

Next, initialize the Capacitor configuration file:

npx cap init

Salin selepas log masuk

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


Salin selepas log masuk

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

npx cap add android

Salin selepas log masuk

Important: Build the web app:

pnpm run build

Salin selepas log masuk

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

Salin selepas log masuk

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

npx cap sync

Salin selepas log masuk

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>

)}

Salin selepas log masuk

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")

Salin selepas log masuk

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])  



Salin selepas log masuk

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()

Salin selepas log masuk

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])

Salin selepas log masuk

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})

Salin selepas log masuk

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>
  )

Salin selepas log masuk

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



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



Salin selepas log masuk

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>



Salin selepas log masuk

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())
    }
  }



....



}

Salin selepas log masuk

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())
    }



Salin selepas log masuk

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>
  )
}



Salin selepas log masuk

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

bulbasaur dragonite

Salin selepas log masuk

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

Salin selepas log masuk

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

Salin selepas log masuk

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.

Dalam artikel ini, kami memperkenalkan pembangunan Android menggunakan alat web, dan rangka kerja pilihan kami ialah Ionic. Kami merangkumi asas komponen Ionik dan Ionik, cara menyediakan Kapasitor jambatan masa jalan asli dan membina APK nyahpepijat.

Jika anda sudah bersedia untuk mendalami Capacitor, anda boleh menemui artikel seterusnya di sini: Capacitor JS: The Bridge Between Web Tech & Native—Android, IOS, PWA

Ini baru permulaan.

Jika anda berminat dengan kandungan yang lebih panjang, eksklusif, praktikal, saya mempunyai peringkat dan siaran yang direka untuk meningkatkan kemahiran pengaturcaraan anda di platform ko-fi.

Atas ialah kandungan terperinci Android Dev dengan Alat web: cara terpantas untuk menghasilkan dengan Ionic React. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan