<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Chayan Mistry on Medium]]></title>
        <description><![CDATA[Stories by Chayan Mistry on Medium]]></description>
        <link>https://medium.com/@chayanmistry?source=rss-b2b849dec896------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ppkR3KYEGUydivV1auQQkA.jpeg</url>
            <title>Stories by Chayan Mistry on Medium</title>
            <link>https://medium.com/@chayanmistry?source=rss-b2b849dec896------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:48:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@chayanmistry/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Arduino Core for STC Micro’s STC8G Family]]></title>
            <link>https://chayanmistry.medium.com/arduino-core-for-stc-micros-stc8g-family-188f534b1413?source=rss-b2b849dec896------2</link>
            <guid isPermaLink="false">https://medium.com/p/188f534b1413</guid>
            <category><![CDATA[8051]]></category>
            <category><![CDATA[arduino-ide]]></category>
            <category><![CDATA[stc8]]></category>
            <category><![CDATA[risc-v]]></category>
            <dc:creator><![CDATA[Chayan Mistry]]></dc:creator>
            <pubDate>Sun, 04 Oct 2026 09:22:03 GMT</pubDate>
            <atom:updated>2026-10-04T09:22:03.418Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGGgm0aKb2iJbJ9k94tliA.png" /></figure><p>STC Micro’s STC8G family of microcontrollers is based on the classic 8051 architecture and is aimed at low-cost embedded applications. While the hardware is inexpensive and capable, the development workflow can be less familiar compared with modern Arduino-supported platforms.</p><p>To make development easier, I developed an <a href="https://github.com/chayanforyou/Arduino-STC8"><strong>unofficial Arduino Core for STC8G microcontrollers</strong></a>, bringing Arduino IDE support to the platform.</p><p>The core uses <strong>SDCC as the compiler backend</strong> and <strong>stcgal for flashing</strong>, allowing sketches to be compiled and uploaded directly from the Arduino IDE. It can be installed through the <strong>Arduino Boards Manager</strong>, so there is no need to manually set up the complete toolchain.</p><p>Once installed, you can select the STC8G board and write familiar Arduino-style code:</p><pre>void setup() {<br>    pinMode(P5_5, OUTPUT);<br>}<br><br>void loop() {<br>    digitalWrite(P5_5, HIGH);<br>    delay(500);<br><br>    digitalWrite(P5_5, LOW);<br>    delay(500);<br>}</pre><p>The project currently provides support for common Arduino functionality such as GPIO, timing, Serial communication, and interrupts.</p><p>The source code and installation instructions are available on GitHub:</p><p><a href="https://github.com/chayanforyou/Arduino-STC8">GitHub - chayanforyou/Arduino-STC8</a></p><p>The goal is simple: <strong>make STC8G development a little easier by bringing the familiar Arduino workflow to these inexpensive 8051-based microcontrollers.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=188f534b1413" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rust in Android Development: Complete Guide]]></title>
            <link>https://chayanmistry.medium.com/rust-in-android-development-complete-guide-5f3313f40e50?source=rss-b2b849dec896------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f3313f40e50</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[jni]]></category>
            <category><![CDATA[rust]]></category>
            <dc:creator><![CDATA[Chayan Mistry]]></dc:creator>
            <pubDate>Tue, 12 May 2026 06:51:55 GMT</pubDate>
            <atom:updated>2026-07-28T06:28:08.053Z</atom:updated>
            <content:encoded><![CDATA[<p>A step-by-step guide to integrating Rust with Android development using JNI (Java Native Interface). This project demonstrates how to write performance-critical code in Rust and call it from Kotlin/Java in an Android application.</p><p><a href="https://chayanmistry.medium.com/rust-in-android-development-complete-guide-5f3313f40e50?source=friends_link&amp;sk=6a96b6a179b52ba1304cac824a09b859"><strong>Don’t have a Medium membership? 👉 Click here to read the full story</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cQtilqAvcSfAah_cbexd0Q.png" /></figure><h3>Prerequisites</h3><p>Before starting, ensure you have:</p><h4>Required Software</h4><ul><li>Android Studio (latest version)</li><li>Rust (1.70+): Install from <a href="https://rustup.rs/">rustup.rs</a></li><li>Android NDK (r25 or later): Install via Android Studio’s SDK Manager</li><li>Cargo (comes with Rust)</li></ul><h4>Verify Installation</h4><pre># Check Rust installation<br>rustc --version<br>cargo --version</pre><h3>Step-by-Step Setup Guide</h3><h4>Step 1: Create a New Android Project</h4><ol><li>Open Android Studio</li><li>Create a new project with Empty Activity template</li><li>Choose Kotlin as the language</li><li>Set minimum SDK to API 24 or higher</li></ol><h4>Step 2: Initialize Rust Project</h4><p>In your project root directory:</p><pre># Create Rust library<br>cargo init --lib</pre><h4>Step 3: Configure Cargo.toml</h4><p>Edit Cargo.toml to specify the library type and dependencies:</p><pre>[package]<br>name = &quot;rustdemo&quot;<br>version = &quot;0.1.0&quot;<br>edition = &quot;2021&quot;<br><br>[lib]<br>crate-type = [&quot;cdylib&quot;]  # Compile as C-compatible dynamic library<br><br>[dependencies]<br>jni = &quot;0.21&quot;  # JNI bindings for Rust<br><br>[profile.release]<br>opt-level = 3      # Maximum optimization<br>lto = true         # Link-time optimization<br>strip = true       # Strip symbols for smaller binary</pre><h4>Step 4: Build Rust Library for Android</h4><p>You’ll compile the Rust library directly using Cargo and place the resulting .so files in the Android project’s jiniLibs directory. This is handled through a build script (see the Building the Project section).</p><h3>Writing Rust Code</h3><h4>Basic Structure</h4><p>Your src/lib.rs should follow this pattern:</p><pre>use jni::JNIEnv;<br>use jni::objects::{JClass, JString};<br>use jni::sys::jstring;<br><br>// ============================================================================<br>// Core Rust Functions (Pure Business Logic)<br>// ============================================================================<br><br>/// Pure Rust function - no JNI dependencies<br>pub fn get_hello_string() -&gt; &amp;&#39;static str {<br>    &quot;Hello from Rust!&quot;<br>}<br><br>/// Pure Rust function with parameters<br>pub fn greet(name: &amp;str) -&gt; String {<br>    format!(&quot;Hello, {}! Greetings from Rust!&quot;, name)<br>}<br><br>// ============================================================================<br>// JNI Wrappers (Bridge between Java and Rust)<br>// ============================================================================<br><br>/// JNI function callable from Java/Kotlin<br>#[no_mangle]<br>pub extern &quot;C&quot; fn Java_com_example_rustdemo_MainActivity_helloFromRust(<br>    env: JNIEnv,<br>    _class: JClass,<br>) -&gt; jstring {<br>    let message = get_hello_string();<br>    let output = env<br>        .new_string(message)<br>        .expect(&quot;Failed to create Java string&quot;);<br>    output.into_raw()<br>}<br><br>/// JNI function with String parameter<br>#[no_mangle]<br>pub extern &quot;C&quot; fn Java_com_example_rustdemo_MainActivity_greetFromRust(<br>    mut env: JNIEnv,<br>    _class: JClass,<br>    name: JString,<br>) -&gt; jstring {<br>    // Convert Java String to Rust String<br>    let name_str: String = env<br>        .get_string(&amp;name)<br>        .expect(&quot;Couldn&#39;t get java string!&quot;)<br>        .into();<br><br>    // Call core Rust function<br>    let greeting = greet(&amp;name_str);<br><br>    // Convert back to Java String<br>    let output = env<br>        .new_string(&amp;greeting)<br>        .expect(&quot;Failed to create Java string!&quot;);<br>    output.into_raw()<br>}</pre><h4>JNI Function Naming Convention</h4><p>JNI functions must follow this naming pattern:</p><pre>Java_&lt;package&gt;_&lt;class&gt;_&lt;method&gt;</pre><p>Example:</p><ul><li>Package: com.example.rustdemo</li><li>Class: MainActivity</li><li>Method: helloFromRust</li><li>Full name: Java_com_example_rustdemo_MainActivity_helloFromRust</li></ul><h4>Best Practices</h4><ol><li>Separate Logic from JNI: Keep pure Rust functions separate from JNI wrappers</li><li>Error Handling: Use .expect() for JNI calls or implement proper error handling</li><li>Memory Management: JNI handles memory; use into_raw() to transfer ownership</li><li>Type Conversions: Use JNI types for parameters and return values</li></ol><h3>Building the Project</h3><p>Create a build script build_rust.sh in your project root:</p><pre>#!/bin/bash<br><br># Build Rust library for Android<br>cd &quot;$(dirname &quot;$0&quot;)&quot;<br><br># Install cargo-ndk if not already installed<br>if ! command -v cargo-ndk &amp;&gt; /dev/null; then<br>    echo &quot;Installing cargo-ndk...&quot;<br>    cargo install cargo-ndk<br>fi<br><br># Add Android targets<br>rustup target add aarch64-linux-android armv7-linux-androideabi x86_64-linux-android i686-linux-android<br><br># Build for all Android targets<br>echo &quot;Building Rust library for Android...&quot;<br>cargo ndk -t arm64-v8a -t armeabi-v7a -t x86 -t x86_64 build --release<br><br># Copy libraries to Android project<br>echo &quot;Copying libraries to Android project...&quot;<br>mkdir -p app/src/main/jniLibs/arm64-v8a<br>mkdir -p app/src/main/jniLibs/armeabi-v7a<br>mkdir -p app/src/main/jniLibs/x86<br>mkdir -p app/src/main/jniLibs/x86_64<br><br>cp target/aarch64-linux-android/release/librustdemo.so app/src/main/jniLibs/arm64-v8a/<br>cp target/armv7-linux-androideabi/release/librustdemo.so app/src/main/jniLibs/armeabi-v7a/<br>cp target/i686-linux-android/release/librustdemo.so app/src/main/jniLibs/x86/<br>cp target/x86_64-linux-android/release/librustdemo.so app/src/main/jniLibs/x86_64/<br><br>echo &quot;Build complete!&quot;</pre><p>Make it executable and run:</p><pre>chmod +x build_rust.sh<br>./build_rust.sh</pre><p>This script:</p><ol><li>Installs cargo-ndk if not already installed</li><li>Adds Android targets to Rust</li><li>Builds the library for all architectures (arm64-v8a, armeabi-v7a, x86, x86_64)</li><li>Copies the compiled .so files to the appropriate jniLibs directories</li></ol><h4>Verify Build Output</h4><p>After building, verify the .so file exists:</p><pre>ls -lh app/src/main/jniLibs/arm64-v8a/librustdemo.so</pre><h3>Calling Rust from Kotlin</h3><h4>Step 1: Declare Native Methods</h4><p>In your Kotlin Activity:</p><pre>class MainActivity : AppCompatActivity() {<br>    companion object {<br>        init {<br>            // Load the Rust library<br>            System.loadLibrary(&quot;rustdemo&quot;)<br>        }<br>    }<br><br>    private lateinit var binding: ActivityMainBinding<br><br>    // Declare native methods<br>    external fun helloFromRust(): String<br>    external fun greetFromRust(name: String): String<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityMainBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br><br>        // Call Rust functions<br>        val message = helloFromRust()<br>        val greeting = greetFromRust(&quot;Android&quot;)<br><br>        binding.textView.text = greeting<br>    }<br>}</pre><h4>Step 2: Load the Library</h4><p>The System.loadLibrary() call in the companion object loads the native library when the class is first accessed.</p><pre>companion object {<br>    init {<br>        System.loadLibrary(&quot;rustdemo&quot;)<br>    }<br>}</pre><h4>Step 3: Call the Functions</h4><pre>val result = helloFromRust()  // Returns &quot;Hello from Rust!&quot;<br>val greeting = greetFromRust(&quot;Android&quot;)  // Returns &quot;Hello, Android! Greetings from Rust!&quot;</pre><h3>Testing</h3><h4>Unit Tests for Rust Code</h4><p>Create src/lib.rs tests:</p><pre>#[cfg(test)]<br>mod tests {<br>    use super::*;<br><br>    #[test]<br>    fn test_get_hello_string() {<br>        assert_eq!(get_hello_string(), &quot;Hello from Rust!&quot;);<br>    }<br><br>    #[test]<br>    fn test_greet() {<br>        let result = greet(&quot;Android&quot;);<br>        assert_eq!(result, &quot;Hello, Android! Greetings from Rust!&quot;);<br>    }<br>}</pre><p>Run tests:</p><pre>cargo test</pre><h4>Android Instrumented Tests</h4><p>Create app/src/androidTest/java/com/example/rustdemo/RustIntegrationTest.kt</p><pre>@RunWith(AndroidJUnit4::class)<br>class RustIntegrationTest {<br>    @Test<br>    fun testHelloFromRust() {<br>        val activity = MainActivity()<br>        val result = activity.helloFromRust()<br>        assert(result.contains(&quot;Rust&quot;))<br>    }<br>}</pre><h3>Performance Considerations</h3><h4>1. Minimize JNI Calls</h4><p>JNI calls have overhead. Batch operations when possible:</p><pre>// ❌ Inefficient: Multiple JNI calls<br>for (i in 0..1000) {<br>    processItem(i)  // JNI call<br>}<br><br>// ✅ Efficient: Single JNI call with batch processing<br>processBatch(items)  // Single JNI call</pre><h4>2. Use Appropriate Data Types</h4><pre>// ❌ Inefficient: String conversion overhead<br>pub fn process_string(s: String) -&gt; String { }<br><br>// ✅ Efficient: Use references when possible<br>pub fn process_string(s: &amp;str) -&gt; String { }</pre><h4>3. Profile Your Code</h4><p>Use Android Profiler to identify bottlenecks:</p><ol><li>Run → Profile</li><li>Select CPU profiler</li><li>Look for JNI overhead</li></ol><h4>4. Optimize Rust Build</h4><pre>[profile.release]<br>opt-level = 3      # Maximum optimization<br>lto = true         # Link-time optimization<br>codegen-units = 1  # Better optimization (slower build)<br>strip = true       # Smaller binary</pre><h3>Resources</h3><h4>Official Documentation</h4><ul><li><a href="https://doc.rust-lang.org/book/">Rust Book</a></li><li><a href="https://docs.oracle.com/javase/8/docs/technotes/guides/jni/">JNI Documentation</a></li><li><a href="https://developer.android.com/ndk/guides">Android NDK Guide</a></li><li><a href="https://docs.rs/jni/latest/jni/">Rust JNI Crate</a></li></ul><h4>Useful Tools</h4><ul><li><a href="https://github.com/bbqsrc/cargo-ndk">cargo-ndk</a>: Simplifies Rust-Android builds</li><li><a href="https://developer.android.com/studio/profile/android-profiler">Android Studio Profiler</a></li><li><a href="https://rust-analyzer.github.io/">Rust Analyzer</a>: IDE support for Rust</li></ul><h4>Learning Resources</h4><ul><li><a href="https://doc.rust-lang.org/rust-by-example/">Rust by Example</a></li><li><a href="https://android-developers.googleblog.com/">Android Developers Blog</a></li><li><a href="https://source.android.com/docs/setup/build/rust">Rust on Android</a></li></ul><h3>Try out GitHub Sample</h3><p><a href="https://github.com/chayanforyou/rust-android-guide">GitHub - chayanforyou/rust-android-guide: Rust + Android integration guide with JNI</a></p><p>Happy coding with Rust and Android! 🦀📱</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f3313f40e50" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Most Developer Stay Stuck at Mid-Level]]></title>
            <link>https://chayanmistry.medium.com/why-most-developer-stay-stuck-at-mid-level-abbd9c28b6ef?source=rss-b2b849dec896------2</link>
            <guid isPermaLink="false">https://medium.com/p/abbd9c28b6ef</guid>
            <category><![CDATA[leadership]]></category>
            <category><![CDATA[careers]]></category>
            <category><![CDATA[career-advice]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[career-growth]]></category>
            <dc:creator><![CDATA[Chayan Mistry]]></dc:creator>
            <pubDate>Thu, 26 Feb 2026 04:48:00 GMT</pubDate>
            <atom:updated>2026-02-26T04:48:00.369Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*iWbqwjQRVjyDcv74" /></figure><h3><strong>Most developers don’t fail.</strong></h3><p><strong>They just stay stuck.</strong></p><p>Same salary.<br>Same responsibilities.<br>Same level.<br>Year after year.</p><p>And it’s not because they lack talent.</p><p>It’s because they focus only on writing code.</p><h3>Here’s what actually separates mid-level from senior:</h3><p><strong>1) Seniors think in systems, not screens</strong><br>They ask: “<em>How does this scale?</em>” not “<em>Does this work?</em>”</p><p><strong>2) They optimize for maintainability</strong><br>Clean architecture, readable code, predictable state flow.</p><p><strong>3) They communicate clearly</strong><br>Good engineers solve problems.<br>Great engineers explain them.</p><p><strong>4) They take ownership</strong><br>If production breaks, they don’t blame they fix and improve the process.</p><p><strong>5) They understand business impact</strong><br>They know why a feature exists, not just how to build it.</p><p><strong>6) They mentor others</strong><br>Seniors solve problems but also they help others solve them too.</p><p><strong>7) They know when NOT to build</strong><br>Sometimes the best code is no code at all.<br>Just ask yourself:</p><blockquote>“Do we actually need this?”</blockquote><h3>Most developers try to improve by learning new frameworks.</h3><p>But real growth comes from:</p><ul><li>Debugging complex problems</li><li>Reading other people’s code</li><li>Designing scalable architecture</li><li>Writing documentation</li><li>Thinking long-term</li></ul><h3>If you want to level up this year,</h3><p>Stop chasing tools.<br>Start building depth.</p><p>What’s one skill that changed your career trajectory?</p><p><a href="https://www.linkedin.com/posts/erdipakrana_softwaredevelopment-careergrowth-developers-activity-7432271179253432320-Cgin/"><strong>Original Source</strong></a><strong> (</strong>Dipak Rana<strong>)</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abbd9c28b6ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building OpenCV 4.12 for Android from Source (with Extra Modules and 16KB Page Size Support)]]></title>
            <link>https://chayanmistry.medium.com/building-opencv-4-12-for-android-from-source-with-extra-modules-and-16kb-page-size-support-9f6cfec85cd2?source=rss-b2b849dec896------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f6cfec85cd2</guid>
            <category><![CDATA[android-ndk]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[cmake]]></category>
            <category><![CDATA[opencv]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Chayan Mistry]]></dc:creator>
            <pubDate>Mon, 01 Sep 2025 10:22:05 GMT</pubDate>
            <atom:updated>2026-07-28T06:26:01.240Z</atom:updated>
            <content:encoded><![CDATA[<p>Starting <strong>November 1st, 2025</strong>, Google requires all Android apps to support <a href="https://developer.android.com/guide/practices/page-sizes"><strong>16KB page sizes</strong></a>. This means if your app uses native libraries, you’ll need to rebuild them to support the new 16 KB page size.</p><p>If you’re working with <strong>OpenCV</strong> and external modules in your Android project, you’ll need to build it from source with the right configuration. This guide walks you through a <strong>step-by-step process</strong> to do just that.</p><p><a href="https://chayanmistry.medium.com/building-opencv-4-12-for-android-from-source-with-extra-modules-and-16kb-page-size-support-9f6cfec85cd2?source=friends_link&amp;sk=451e2536419a33d2becb2794e6edf77e"><strong>Don’t have a Medium membership? 👉 Click here to read the full story</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZcSE7CV9zyD_ZqMBIVU86w.png" /></figure><h3>Tools &amp; Versions Used</h3><ul><li><strong>CMake</strong>: 3.22.1</li><li><strong>Ninja</strong>: 1.10.0</li><li><strong>Python</strong>: 3.13.2</li><li><strong>Java</strong>: 17.0.12</li><li><strong>Android SDK</strong>: Installed with Android Studio Meerkat 2024.3.1</li><li><strong>Android NDK:</strong> r27 (27.2.12479018)</li></ul><h3>Step 1: Install Prerequisites</h3><h4>On Ubuntu/Debian</h4><pre>sudo apt update<br>sudo apt install -y python3 python3-pip openjdk-17-jdk</pre><h4>On macOS</h4><pre>brew install python<br>brew install openjdk@17</pre><h4>Required Android SDK Tools</h4><p>Inside <strong>Android Studio → SDK</strong> Tools, make sure you have:</p><ul><li>Android SDK Build-Tools 36.0.0</li><li>NDK 27.2.12479018</li><li>CMake 3.22.1</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*X6cwpd_OgizvNQF0SEqVlQ.png" /></figure><h3>Step 2: Download OpenCV Source</h3><ul><li><a href="https://github.com/opencv/opencv/releases/tag/4.12.0">OpenCV 4.12 source</a></li><li><a href="https://github.com/opencv/opencv_contrib/releases/tag/4.12.0">OpenCV Contrib (extra modules)</a></li></ul><h3>Step 3: Setup Build Directory</h3><p>Create a directory for your build:</p><pre>mkdir opencv_build &amp;&amp; cd opencv_build</pre><p>Unzip both opencv and opencv_contrib inside opencv_build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/1*2oVxBGX7hlqb86ygnSDLlA.png" /></figure><h3>Step 4: Configure Build Script</h3><p>Download the build script (opencv_android_build.sh) and the NDK config (ndk-27.config.py) into your opencv_build directory.</p><p><strong>Build Script Example </strong>(opencv_android_build.sh):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af18c780d6c94aa874650236fd4a7fc6/href">https://medium.com/media/af18c780d6c94aa874650236fd4a7fc6/href</a></iframe><p>NDK Config Example (ndk-27.config.py):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/582fac6f352960215751dabd14dfe2af/href">https://medium.com/media/582fac6f352960215751dabd14dfe2af/href</a></iframe><p>In my setup, I’m using NDK r27 with CMake argument</p><pre>-DANDROID_SUPPORT_FLEXIBLE_PAGE_SIZES=ON</pre><p>This flag ensures compatibility with Google’s new <a href="https://developer.android.com/guide/practices/page-sizes#compile-r27">16KB page size requirement.</a></p><p>Make the script executable and run it:</p><pre>chmod +x opencv_android_build.sh<br>./opencv_android_build.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bD-U5xZ1tycZpjz0dy-9EA.png" /></figure><p>After the build completes, a new <strong>OpenCV-android-sdk</strong> directory will appear inside the <strong>opencv-android-build</strong> folder.</p><p>This folder contains the prebuilt OpenCV Android SDK, which you can now import into your Android Studio project.</p><h3>Step 5: Setup Your Android Project</h3><ul><li>Create a new Android project in Android Studio (skip if you already have one).</li><li>Import OpenCV as a module:<br>- File → New → Import Module<br>- Select OpenCV-android-sdk/sdk<br>- Rename the module (e.g., :openCVLibrary412)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*p8t-oYJYRX3muPUj6N02lw.png" /></figure><h3>Step 6: Add OpenCV Dependency</h3><ul><li>Open <strong>Project Structure → Dependencies</strong></li><li>Select your app module → click <strong>+ → Module Dependency</strong></li><li>Choose the OpenCV library module you just imported</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*h2Dklh9gZhNueSKUA7IcwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*zAJ1brXLCbnHgXmifdeqjA.png" /></figure><h3>Step 7: Fix Gradle Sync Issues</h3><p>Open the imported module’s build.gradle and:</p><ul><li>Update compileSdkVersion and targetSdkVersion to your installed SDK version.</li><li>Add jvmTarget = &quot;17&quot; if you’re using Kotlin:</li></ul><pre>kotlinOptions {<br>    jvmTarget = &quot;17&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xOOkWBepP_BPPpLGT_4M7Q.png" /></figure><p>Sync Gradle to apply changes.</p><h3>Step 8: Add Required Permissions</h3><p>In AndroidManifest.xml:</p><pre>&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot;/&gt;<br><br>&lt;uses-feature android:name=&quot;android.hardware.camera&quot; android:required=&quot;false&quot;/&gt;<br>&lt;uses-feature android:name=&quot;android.hardware.camera.autofocus&quot; android:required=&quot;false&quot;/&gt;<br>&lt;uses-feature android:name=&quot;android.hardware.camera.front&quot; android:required=&quot;false&quot;/&gt;<br>&lt;uses-feature android:name=&quot;android.hardware.camera.front.autofocus&quot; android:required=&quot;false&quot;/&gt;</pre><h3>Step 9: <strong>Try out Sample</strong></h3><p>To confirm that OpenCV is integrated correctly, try out my GitHub sample <a href="https://github.com/chayanforyou/OpenCvObjectTracking"><strong>OpenCvObjectTracking</strong></a>. Build the app, run it on a test device, grant camera permissions, and verify that everything works as expected. 🎉</p><p><a href="https://github.com/chayanforyou/OpenCvObjectTracking">GitHub - chayanforyou/OpenCvObjectTracking</a></p><p>Quickly update your app main activity with the code below.</p><pre>package io.github.chayanforyou.tracking<br><br>import android.Manifest<br>import android.annotation.SuppressLint<br>import android.content.pm.PackageManager<br>import android.graphics.Canvas<br>import android.graphics.Color<br>import android.graphics.ImageFormat<br>import android.graphics.Paint<br>import android.graphics.Point<br>import android.graphics.SurfaceTexture<br>import android.hardware.camera2.CameraAccessException<br>import android.hardware.camera2.CameraCaptureSession<br>import android.hardware.camera2.CameraDevice<br>import android.hardware.camera2.CameraManager<br>import android.hardware.camera2.CaptureRequest<br>import android.media.ImageReader<br>import android.os.Bundle<br>import android.util.Size<br>import android.view.MotionEvent<br>import android.view.Surface<br>import android.view.TextureView<br>import android.widget.Toast<br>import androidx.activity.result.contract.ActivityResultContracts<br>import androidx.appcompat.app.AppCompatActivity<br>import androidx.core.app.ActivityCompat<br>import org.opencv.android.OpenCVLoader<br>import org.opencv.core.Core<br>import org.opencv.core.Mat<br>import org.opencv.core.MatOfByte<br>import org.opencv.core.Rect2d<br>import org.opencv.imgcodecs.Imgcodecs<br>import org.opencv.imgproc.Imgproc<br>import org.opencv.tracking.legacy_Tracker<br>import org.opencv.tracking.legacy_TrackerCSRT<br>import org.opencv.tracking.legacy_TrackerKCF<br>import org.opencv.tracking.legacy_TrackerMIL<br>import org.opencv.tracking.legacy_TrackerMOSSE<br>import org.opencv.tracking.legacy_TrackerMedianFlow<br>import org.opencv.tracking.legacy_TrackerTLD<br>import kotlin.math.max<br>import kotlin.math.min<br><br>enum class Drawing { DRAWING, TRACKING, CLEAR }<br><br>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var textureView: TextureView<br>    private lateinit var trackingOverlay: OverlayView<br><br>    private var cameraDevice: CameraDevice? = null<br>    private var captureSession: CameraCaptureSession? = null<br>    private var previewRequestBuilder: CaptureRequest.Builder? = null<br>    private var imageGrab: Mat? = null<br>    private var imageReader: ImageReader? = null<br>    private var tracker: legacy_Tracker? = null<br>    private var drawing = Drawing.DRAWING<br>    private val camResolution = Size(1280, 720)<br>    private val points = arrayOf(Point(0, 0), Point(0, 0))<br>    private var processing = false<br>    private var targetLocked = false<br>    private var selectedTracker = &quot;TrackerMedianFlow&quot;  // OpenCV tracking algorithm<br><br>    private val requestPermissionLauncher =<br>        registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted -&gt;<br>            if (granted) {<br>                openCamera()<br>            } else {<br>                Toast.makeText(this, &quot;Sorry!!!, you can&#39;t use this app without granting permission&quot;, Toast.LENGTH_LONG).show()<br>            }<br>        }<br><br>    private val textureListener = object : TextureView.SurfaceTextureListener {<br>        override fun onSurfaceTextureAvailable(surface: SurfaceTexture, width: Int, height: Int) {<br>            openCamera()<br>        }<br>        override fun onSurfaceTextureSizeChanged(surface: SurfaceTexture, width: Int, height: Int) {}<br>        override fun onSurfaceTextureDestroyed(surface: SurfaceTexture) = false<br>        override fun onSurfaceTextureUpdated(surface: SurfaceTexture) {}<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        if (!OpenCVLoader.initLocal()) {<br>            Toast.makeText(this, &quot;OpenCV initialization failed!&quot;, Toast.LENGTH_LONG).show()<br>            return<br>        }<br>        setContentView(R.layout.activity_main)<br>        textureView = findViewById(R.id.texture)<br>        trackingOverlay = findViewById(R.id.tracking_overlay)<br>        textureView.surfaceTextureListener = textureListener<br>    }<br><br>    override fun onDestroy() {<br>        closeCamera()<br>        super.onDestroy()<br>    }<br><br>    private fun openCamera() {<br>        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {<br>            requestPermissionLauncher.launch(Manifest.permission.CAMERA)<br>            return<br>        }<br><br>        val manager = getSystemService(CAMERA_SERVICE) as CameraManager<br>        try {<br>            val cameraId = manager.cameraIdList.first()<br>            manager.openCamera(cameraId, stateCallback, null)<br>        } catch (e: CameraAccessException) {<br>            e.printStackTrace()<br>        }<br>    }<br><br>    private fun closeCamera() {<br>        captureSession?.close()<br>        captureSession = null<br>        cameraDevice?.close()<br>        cameraDevice = null<br>        imageReader?.close()<br>        imageReader = null<br>    }<br><br>    private val stateCallback = object : CameraDevice.StateCallback() {<br>        override fun onOpened(camera: CameraDevice) {<br>            cameraDevice = camera<br>            createCameraPreview()<br>        }<br><br>        override fun onDisconnected(camera: CameraDevice) {<br>            cameraDevice?.close()<br>        }<br><br>        override fun onError(camera: CameraDevice, error: Int) {<br>            cameraDevice?.close()<br>            cameraDevice = null<br>        }<br>    }<br><br>    @SuppressLint(&quot;ClickableViewAccessibility&quot;)<br>    private fun createCameraPreview() {<br>        try {<br>            val texture = textureView.surfaceTexture<br>            texture?.setDefaultBufferSize(camResolution.width, camResolution.height)<br>            val surface = Surface(texture)<br>            previewRequestBuilder = cameraDevice?.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)?.apply {<br>                addTarget(surface)<br>            }<br>            imageReader = ImageReader.newInstance(camResolution.width, camResolution.height, ImageFormat.JPEG, 2).apply {<br>                setOnImageAvailableListener(onImageAvailableListener, null)<br>            }<br>            previewRequestBuilder?.addTarget(imageReader!!.surface)<br>            cameraDevice?.createCaptureSession(<br>                listOf(surface, imageReader!!.surface),<br>                object : CameraCaptureSession.StateCallback() {<br>                    override fun onConfigured(session: CameraCaptureSession) {<br>                        if (cameraDevice == null) return<br>                        captureSession = session<br>                        previewRequestBuilder?.set(<br>                            CaptureRequest.CONTROL_AF_MODE,<br>                            CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE<br>                        )<br>                        previewRequestBuilder?.set(<br>                            CaptureRequest.CONTROL_AE_MODE,<br>                            CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH<br>                        )<br>                        try {<br>                            session.setRepeatingRequest(<br>                                previewRequestBuilder!!.build(),<br>                                null,<br>                                null<br>                            )<br>                        } catch (e: CameraAccessException) {<br>                            e.printStackTrace()<br>                        }<br>                    }<br><br>                    override fun onConfigureFailed(session: CameraCaptureSession) {<br>                        Toast.makeText(this@MainActivity, &quot;Configuration change&quot;, Toast.LENGTH_SHORT).show()<br>                    }<br>                },<br>                null<br>            )<br><br>            trackingOverlay.addCallback(object : OverlayView.DrawCallback {<br>                override fun drawCallback(canvas: Canvas) {<br>                    if (drawing != Drawing.CLEAR) {<br>                        val paint = Paint().apply {<br>                            color = Color.BLUE<br>                            strokeWidth = 10f<br>                            style = Paint.Style.STROKE<br>                        }<br>                        canvas.drawRect(<br>                            points[0].x.toFloat(),<br>                            points[0].y.toFloat(),<br>                            points[1].x.toFloat(),<br>                            points[1].y.toFloat(),<br>                            paint<br>                        )<br>                        if (drawing == Drawing.TRACKING) {<br>                            paint.color = Color.GREEN<br>                            canvas.drawLine(<br>                                (points[0].x + points[1].x) / 2f,<br>                                0f,<br>                                (points[0].x + points[1].x) / 2f,<br>                                trackingOverlay.height.toFloat(),<br>                                paint<br>                            )<br>                            canvas.drawLine(<br>                                0f,<br>                                (points[0].y + points[1].y) / 2f,<br>                                trackingOverlay.width.toFloat(),<br>                                (points[0].y + points[1].y) / 2f,<br>                                paint<br>                            )<br>                        }<br>                    }<br>                }<br>            })<br><br>            trackingOverlay.setOnTouchListener { _, event -&gt;<br>                val x = event.x.toInt()<br>                val y = event.y.toInt()<br>                when (event.action and MotionEvent.ACTION_MASK) {<br>                    MotionEvent.ACTION_DOWN -&gt; if (!targetLocked) {<br>                        drawing = Drawing.DRAWING<br>                        points[0].set(x, y)<br>                        points[1].set(x, y)<br>                        trackingOverlay.invalidate()<br>                    }<br>                    MotionEvent.ACTION_MOVE -&gt; if (!targetLocked) {<br>                        points[1].set(x, y)<br>                        trackingOverlay.invalidate()<br>                    }<br>                    MotionEvent.ACTION_UP -&gt; if (!targetLocked) {<br>                        drawing = Drawing.CLEAR<br>                        trackingOverlay.invalidate()<br>                    }<br>                    MotionEvent.ACTION_POINTER_DOWN -&gt; {<br>                        targetLocked = !targetLocked<br>                        Toast.makeText(this@MainActivity, &quot;Target ${if (targetLocked) &quot;LOCKED&quot; else &quot;UNLOCKED&quot;}&quot;, Toast.LENGTH_SHORT).show()<br>                        drawing = Drawing.DRAWING<br>                        trackingOverlay.invalidate()<br>                    }<br>                }<br>                true<br>            }<br>        } catch (e: CameraAccessException) {<br>            e.printStackTrace()<br>        }<br>    }<br><br>    private val onImageAvailableListener = ImageReader.OnImageAvailableListener { reader -&gt;<br>        val image = reader.acquireLatestImage() ?: return@OnImageAvailableListener<br>        if (processing) {<br>            image.close()<br>            return@OnImageAvailableListener<br>        }<br>        processing = true<br><br>        if (targetLocked) {<br>            val bb = image.planes[0].buffer<br>            val data = ByteArray(bb.remaining()).also { bb.get(it) }<br>            imageGrab = Imgcodecs.imdecode(MatOfByte(*data), Imgcodecs.IMREAD_UNCHANGED)<br>            Core.transpose(imageGrab, imageGrab)<br>            Core.flip(imageGrab, imageGrab, 1)<br>            Imgproc.resize(imageGrab, imageGrab, org.opencv.core.Size(240.0, 320.0))<br>        }<br>        image.close()<br>        processing()<br>    }<br><br>    private fun processing() {<br>        if (targetLocked &amp;&amp; imageGrab != null) {<br>            if (drawing == Drawing.DRAWING) {<br>                val minX = (min(points[0].x.toFloat(), points[1].x.toFloat()) / trackingOverlay.width * imageGrab!!.cols()).toInt()<br>                val minY = (min(points[0].y.toFloat(), points[1].y.toFloat())/ trackingOverlay.height * imageGrab!!.rows()).toInt()<br>                val maxX = (max(points[0].x.toFloat(), points[1].x.toFloat())/ trackingOverlay.width * imageGrab!!.cols()).toInt()<br>                val maxY = (max(points[0].y.toFloat(), points[1].y.toFloat()) / trackingOverlay.height * imageGrab!!.rows()).toInt()<br><br>                val initRectangle = Rect2d(<br>                    minX.toDouble(),<br>                    minY.toDouble(),<br>                    (maxX - minX).toDouble(),<br>                    (maxY - minY).toDouble()<br>                )<br>                val imageGrabInit = Mat().also { imageGrab?.copyTo(it) }<br><br>                tracker = when (selectedTracker) {<br>                    &quot;TrackerMedianFlow&quot; -&gt; legacy_TrackerMedianFlow.create()<br>                    &quot;TrackerCSRT&quot; -&gt; legacy_TrackerCSRT.create()<br>                    &quot;TrackerKCF&quot; -&gt; legacy_TrackerKCF.create()<br>                    &quot;TrackerMOSSE&quot; -&gt; legacy_TrackerMOSSE.create()<br>                    &quot;TrackerTLD&quot; -&gt; legacy_TrackerTLD.create()<br>                    &quot;TrackerMIL&quot; -&gt; legacy_TrackerMIL.create()<br>                    else -&gt; legacy_TrackerMedianFlow.create()<br>                }<br>                tracker!!.init(imageGrabInit, initRectangle)<br>                drawing = Drawing.TRACKING<br>            } else {<br>                val trackingRectangle = Rect2d(0.0, 0.0, 1.0, 1.0)<br>                tracker?.update(imageGrab!!, trackingRectangle)<br>                points[0].x = (trackingRectangle.x * trackingOverlay.width / imageGrab!!.cols()).toInt()<br>                points[0].y = (trackingRectangle.y * trackingOverlay.height / imageGrab!!.rows()).toInt()<br>                points[1].x = points[0].x + (trackingRectangle.width * trackingOverlay.width / imageGrab!!.cols()).toInt()<br>                points[1].y = points[0].y + (trackingRectangle.height * trackingOverlay.height / imageGrab!!.rows()).toInt()<br>                trackingOverlay.invalidate()<br>            }<br>        } else {<br>            tracker?.clear()<br>            tracker = null<br>        }<br>        processing = false<br>    }<br>}</pre><p>Then create a new class called OverlayView.kt and copy the code below into it.</p><pre>package io.github.chayanforyou.tracking<br><br>import android.content.Context<br>import android.graphics.Canvas<br>import android.util.AttributeSet<br>import android.view.View<br><br>class OverlayView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :<br>    View(context, attrs) {<br><br>    private val callbacks = mutableListOf&lt;DrawCallback&gt;()<br><br>    fun addCallback(callback: DrawCallback) {<br>        callbacks.add(callback)<br>    }<br><br>    override fun draw(canvas: Canvas) {<br>        super.draw(canvas)<br>        synchronized(this) {<br>            callbacks.forEach { it.drawCallback(canvas) }<br>        }<br>    }<br><br>    interface DrawCallback {<br>        fun drawCallback(canvas: Canvas)<br>    }<br>}</pre><p>Finally, update your app main activity layout file with the layout code below.</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:keepScreenOn=&quot;true&quot;<br>    android:orientation=&quot;vertical&quot;&gt;<br><br>    &lt;TextureView<br>        android:id=&quot;@+id/texture&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;wrap_content&quot; /&gt;<br><br>    &lt;io.github.chayanforyou.tracking.OverlayView<br>        android:id=&quot;@+id/tracking_overlay&quot;<br>        android:layout_width=&quot;match_parent&quot;<br>        android:layout_height=&quot;match_parent&quot; /&gt;<br><br>&lt;/FrameLayout&gt;</pre><h3><strong>Step 10: Test the App</strong></h3><p>Finally, hit the run button and run the app on your test device.</p><blockquote>Don’t forget runtime permissions on Android 6.0+</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fa5xlCG2g-Uk%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fshorts%2Fa5xlCG2g-Uk%3Ffeature%3Dshare&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fa5xlCG2g-Uk%2Fhq2.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/dacbfcb2390ff701ca7a808f452c5291/href">https://medium.com/media/dacbfcb2390ff701ca7a808f452c5291/href</a></iframe><h3>Compatibility Check: Is Your App’s Native Code Ready for 16KB Page Size?</h3><h4>Step 1: Identify Native Code</h4><p>First, check whether your app includes any <strong>native libraries</strong>.</p><ul><li>If your Android app contains .so files (shared object files), it means it uses native code.</li><li>You can verify this using <strong>Android Studio’s APK Analyzer</strong>:<br>1. Drag and drop your APK into Android Studio.<br>2. The APK Analyzer window will open automatically.<br>3. Look under the lib/ directory to see if .so files are present.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6sGt9Da3M8rNbKlsaS_8Qg.png" /></figure><h4>Step 2: Check Compatibility with 16KB Page Size</h4><p>Now let’s confirm whether the .so files are aligned for 16KB pages.</p><ul><li>Download and save the script check_elf_alignment.sh.<br><em>(Use the modified version below for improved readability.)</em></li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f27428fdb8adf4dc3c771aec6a8f30a5/href">https://medium.com/media/f27428fdb8adf4dc3c771aec6a8f30a5/href</a></iframe><ul><li>Make the script executable:<br>chmod +x check_elf_alignment.sh</li><li>Run the script on your APK:<br>./check_elf_alignment.sh APK_NAME.apk</li></ul><p>You’ll see results similar to this:</p><ul><li><strong>UNALIGNED</strong> → supports <strong>4KB page size only</strong></li><li><strong>ALIGNED</strong> → supports <strong>16KB page size</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y9VcP4yK-hDiexvZG-O2Ow.png" /></figure><p>That’s it! You’ve successfully built <strong>OpenCV 4.12 for Android with extra modules and 16KB page size support</strong>.</p><p>If you found this guide helpful, please hit the 👏 button and share so other developers can find it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f6cfec85cd2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>