<?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 Arpit Johri on Medium]]></title>
        <description><![CDATA[Stories by Arpit Johri on Medium]]></description>
        <link>https://medium.com/@arpitjohri?source=rss-42329c936f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Li0r-cTkKOjE48mXnRg72w.jpeg</url>
            <title>Stories by Arpit Johri on Medium</title>
            <link>https://medium.com/@arpitjohri?source=rss-42329c936f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 15:46:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@arpitjohri/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[Efficient SMS Message Processing with Android WorkManager]]></title>
            <link>https://medium.com/@arpitjohri/efficient-sms-message-processing-with-android-workmanager-b687dcb1bb0e?source=rss-42329c936f------2</link>
            <guid isPermaLink="false">https://medium.com/p/b687dcb1bb0e</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[sms]]></category>
            <category><![CDATA[workmanager]]></category>
            <dc:creator><![CDATA[Arpit Johri]]></dc:creator>
            <pubDate>Sun, 05 Nov 2023 18:25:18 GMT</pubDate>
            <atom:updated>2023-11-05T18:25:18.233Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*sJtVPJ66WPG2_Lxv.jpg" /></figure><p>In the world of Android app development, managing background tasks efficiently is a crucial aspect of building responsive and reliable applications. One common use case is processing SMS messages in the background while ensuring that the process is both seamless and unobtrusive for users. In this article, we’ll explore an Android worker class that accomplishes this task using WorkManager, a powerful library for managing background tasks, and Dagger Hilt for dependency injection.</p><h3>Introduction</h3><p>The SMSReadUploadWorker is an Android worker class designed to process SMS messages by reading them from the device&#39;s inbox and uploading them to a server. This worker is a part of an Android application and uses various technologies and libraries to achieve its functionality.</p><h3>Worker Setup</h3><p>Before diving into the worker’s code, let’s discuss its setup:</p><ul><li>HiltWorker: The @HiltWorker annotation denotes that this class can receive dependency injection via Dagger Hilt.</li><li>Dependencies: The worker class constructor receives several dependencies, including the repository for sending messages, an I/O dispatcher for performing background operations, and a PersistenceManager for managing application data.</li><li>I/O Dispatcher: The ioDispatcher is used for running I/O-bound operations on a background thread, ensuring that the worker&#39;s tasks do not block the main thread.</li><li>Constraints: The worker is configured with constraints, ensuring that it only runs when a network connection is available. This is important for ensuring that the worker’s tasks can communicate with the server.</li></ul><h3>Background Task</h3><p>The core functionality of the SMSReadUploadWorker is performed within the doWork method. Here&#39;s an overview of what this method accomplishes:</p><ol><li>Token Validation: The worker starts by validating a token (retrieved from the PersistenceManager). If the token is empty, the worker immediately fails. This ensures that the worker only runs with valid credentials.</li><li>Reading SMS Messages: The worker retrieves SMS messages from the device’s inbox in batches of a specified size. The batch size can be adjusted based on the specific requirements of the application.</li><li>Uploading Messages: Once a batch of messages is collected, the worker sends them to the server using the repository.sendMessages function. The messages are then marked as processed.</li><li>Retry Logic: If any exceptions occur during the background task, the worker handles them gracefully. It allows for a limited number of retries (SYNC_WORK_MAX_ATTEMPTS) before eventually failing.</li></ol><h3>Reading SMS Messages</h3><p>To read SMS messages, the worker uses the Android ContentResolver and the Telephony provider to query the device&#39;s SMS inbox. It iterates through the messages, retrieving data such as the sender&#39;s address, message body, and timestamp. These messages are stored in an ArrayList for batch processing.</p><h3>Batch Processing</h3><p>To improve efficiency and avoid overloading the server, the worker processes SMS messages in batches. Once a batch is ready, it calls the sendMessageBatch function to upload the messages to the server. The function also keeps track of the last processed SMS index to continue from where it left off in case the worker is retried.</p><h3>Uploading Messages</h3><p>Messages are uploaded to the server using the repository.sendMessages function. This function is part of the application&#39;s domain layer and handles the communication with the server. The worker&#39;s code also handles various data states returned by the repository, such as success, error, or loading states.</p><h3>Worker Initialization</h3><p>The worker is configured to run under certain constraints, ensuring that it only operates when specific conditions are met. The getOneTimeWorkRequest and getPeriodicWorkRequest functions provide the necessary configurations for one-time and periodic background work, respectively.</p><h3>Conclusion</h3><p>The SMSReadUploadWorker showcases how to efficiently process SMS messages in the background using WorkManager and Dagger Hilt. It is a robust solution for handling SMS-related tasks in Android applications. By exploring this code, developers can gain a deeper understanding of how to manage background tasks, handle retries, and communicate with servers in a reliable and efficient manner.</p><p>This worker can be customized and extended to meet the specific requirements of different applications. Whether you’re building a messaging app, a productivity tool, or any other Android application that involves SMS processing, the principles demonstrated in this article provide a solid foundation for efficient background task management.</p><p>By implementing background tasks in a well-structured and efficient manner, you can ensure that your Android application remains responsive and delivers a seamless user experience. The combination of WorkManager and Dagger Hilt simplifies the development of such tasks, allowing developers to focus on the core functionality of their applications.</p><p>Here is the full code</p><pre>/**<br> * @author Arpit Johri<br> */<br><br><br>@HiltWorker<br>class SMSReadUploadWorker @AssistedInject constructor(<br>    @Assisted ctx: Context,<br>    @Assisted params: WorkerParameters,<br>    private val repository: Repository,<br>    @Dispatcher(AppDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,<br>    private val persistenceManager: PersistenceManager<br>): CoroutineWorker(ctx, params) {<br><br>    override suspend fun doWork(): Result = withContext(ioDispatcher) {<br>        return@withContext try {<br>            // Retrieve inbox messages in batches of 100 (adjust this as needed)<br>            val token = persistenceManager.getStringToPreferences(PersistenceManager.KEY_TOKEN, &quot;&quot;)<br>            if (token.isEmpty())<br>                Result.failure()<br>            if (readMessagesFromInboxAndSendInBatches(BATCH_SIZE)) {<br>                Result.success()<br>            } else {<br>                val lastAttempt = runAttemptCount &gt;= SYNC_WORK_MAX_ATTEMPTS<br>                if (lastAttempt)<br>                    Result.failure()<br>                else<br>                    Result.retry()<br>            }<br>            Result.success()<br>        } catch (e: Exception) {<br>            // Handle exceptions<br>            Result.failure()<br>        }<br>    }<br><br>    private suspend fun readMessagesFromInboxAndSendInBatches(batchSize: Int): Boolean {<br>        val contentResolver = applicationContext.contentResolver<br>        val inboxUri = Uri.parse(&quot;content://sms/inbox&quot;)<br>        val messages = arrayListOf&lt;MessageInbox&gt;()<br><br>        val cursor = contentResolver.query(<br>            inboxUri,<br>            null,<br>            null,<br>            null,<br>            &quot;date ASC&quot; // Order messages by date in ascending order<br>        )<br><br>        cursor?.use { c -&gt;<br>            val idColumnIndex = c.getColumnIndex(Telephony.Sms.Inbox._ID)<br>            val dateColumnIndex = c.getColumnIndex(Telephony.Sms.Inbox.DATE)<br>            val addressColumnIndex = c.getColumnIndex(Telephony.Sms.Inbox.ADDRESS)<br>            val bodyColumnIndex = c.getColumnIndex(Telephony.Sms.Inbox.BODY)<br><br>            var messageCount = 0<br>            val lastSMSIndex = persistenceManager.getIntToPreferences(LAST_SMS_INDEX, 0)<br>            c.moveToPosition(lastSMSIndex)<br>            Timber.i(&quot;lastSMSIndex $lastSMSIndex&quot;)<br>            Timber.i(&quot;COUNT ${c.count}&quot;)<br>            if (c.isAfterLast.not()) {<br>                MainActivityUtils.trackSMSRead(applicationContext, &quot;$lastSMSIndex / ${c.count}&quot;)<br>            }<br>            while (c.moveToNext()) {<br><br>                val id = c.getString(idColumnIndex)<br>                val receivedTimestamp = c.getLong(dateColumnIndex)<br>                val address = c.getString(addressColumnIndex)<br>                val body = c.getString(bodyColumnIndex)<br><br><br>                // Create a Message object and add it to the list<br>                val message = MessageInbox(<br>                    sender = address,<br>                    body =  body,<br>                    smsTimestamp = receivedTimestamp)<br><br>                messages.add(message)<br><br>                messageCount++<br><br>                // If we&#39;ve reached the batch size, send the batch<br>                if (messageCount &gt;= batchSize || (c.count - lastSMSIndex in 1 until batchSize)) {<br>                    sendMessageBatch(messages = messages,<br>                        offset = lastSMSIndex,<br>                        limit = messages.size,<br>                        size = c.count)<br>                    persistenceManager.saveIntToPreference(LAST_SMS_INDEX, c.position)<br>                    return true//send this value based on API response<br>                }<br>            }<br>        }<br><br>        return false<br>    }<br><br>    private suspend fun sendMessageBatch(messages: ArrayList&lt;MessageInbox&gt;, offset: Int, limit: Int, size: Int) {<br>        repository.sendMessages(SmsUploadRequest(<br>            userSmsList = messages, offset = offset, limit = limit, size = size<br>        )).collect { dataState -&gt;<br>            when (dataState) {<br>                is DataState.Success -&gt; {<br>                    Timber.i(&quot;sendMessageBatch SUCCESS&quot;)<br>                }<br>                is DataState.Error -&gt; {<br>                    Timber.i(&quot;sendMessageBatch ERROR&quot;)<br>                }<br>                is DataState.Empty -&gt; {}<br>                is DataState.Loading -&gt; {<br>                    Timber.i(&quot;sendMessageBatch LOADING&quot;)<br>                }<br>            }<br>        }<br>    }<br><br>    companion object {<br>        private val constraints = Constraints.Builder()<br>            .setRequiredNetworkType(NetworkType.CONNECTED)<br>            /*.setRequiresDeviceIdle(true)<br>            .setRequiresCharging(true)<br>            .setRequiresBatteryNotLow(true)*/<br>            .build()<br>        fun getOneTimeWorkRequest() = OneTimeWorkRequestBuilder&lt;SMSReadUploadWorker&gt;()<br>            .setConstraints(constraints)<br>            .build()<br><br>        fun getPeriodicWorkRequest() = PeriodicWorkRequestBuilder&lt;SMSReadUploadWorker&gt;(<br>            10,<br>            TimeUnit.MINUTES,<br>            5,<br>            TimeUnit.MINUTES<br>        ).setConstraints(constraints)<br>            .build()<br>    }<br><br><br>}</pre><p>Next thing is WorkManagerInitializer</p><pre>object WorkManagerInitializer : Initializer&lt;WorkManager&gt; {<br>    override fun create(@ApplicationContext context: Context): WorkManager {<br>        val workerFactory = getWorkerFactory(appContext = context.applicationContext)<br>        val config = Configuration.Builder()<br>            .setWorkerFactory(workerFactory)<br>            .build()<br>        WorkManager.initialize(context, config)<br>        Timber.i(&quot;Hilt Init WorkManager initialized by Hilt&quot;)<br>        return WorkManager.getInstance(context)<br>    }<br><br>    private fun getWorkerFactory(appContext: Context): HiltWorkerFactory {<br>        val workManagerEntryPoint = EntryPointAccessors.fromApplication(<br>            appContext,<br>            WorkManagerInitializerEntryPoint::class.java<br>        )<br>        return workManagerEntryPoint.hiltWorkerFactory()<br>    }<br><br>    @InstallIn(SingletonComponent::class)<br>    @EntryPoint<br>    interface WorkManagerInitializerEntryPoint {<br>        fun hiltWorkerFactory(): HiltWorkerFactory<br>    }<br><br>    override fun dependencies(): List&lt;Class&lt;out Initializer&lt;*&gt;&gt;&gt; {<br>        // No dependencies on other libraries.<br>        return mutableListOf()<br>    }<br>}</pre><p>The WorkManagerInitializer class is used to initialise WorkManager with Hilt&#39;s HiltWorkerFactory in an Android app. This is a common setup when working with WorkManager and Dagger Hilt for dependency injection. Let&#39;s break down what this code does:</p><ol><li>WorkManagerInitializer implements the Initializer interface. Initializers are used in Android to set up and configure components in a specific order when the application starts.</li><li>In the create method, the @ApplicationContext annotation is used to inject the application context. This context is used to create a WorkManager instance and configure it.</li><li>The getWorkerFactory function retrieves the HiltWorkerFactory by using Hilt&#39;s EntryPointAccessors from the WorkManagerInitializerEntryPoint entry point. The hiltWorkerFactory function is defined within the entry point.</li><li>Inside the create method, a Configuration object is created, and the HiltWorkerFactory is set as the worker factory for WorkManager.</li><li>WorkManager is then initialised with the provided configuration and the application context.</li><li>A log message is printed indicating that WorkManager has been initialised with Hilt.</li><li>The dependencies function specifies that this initialiser has no dependencies on other libraries.</li></ol><p>This initializer is an essential part of setting up WorkManager to work seamlessly with Dagger Hilt, ensuring that Hilt can provide the required dependencies for worker classes when they are executed. It’s a best practice to initialize WorkManager in this way when working with Dagger Hilt in your Android app.</p><p>Now all it requires is to Initialise the WorkManagerInitializer component in your Application class by calling</p><pre>AppInitializer.getInstance(this).initializeComponent(WorkManagerInitializer::class.java)</pre><p>Then in your Activity Class you can start the worker as per your requirement using</p><pre>private fun startReadUploadSMSWorker() {<br>        WorkManager.getInstance(this).enqueueUniquePeriodicWork(<br>                SMSReadUploadWorker::class.java.name,<br>                ExistingPeriodicWorkPolicy.KEEP,<br>                SMSReadUploadWorker.getPeriodicWorkRequest()<br>            )<br>    }</pre><p>Don’t forget If you want to disable android.startup completely</p><pre>&lt;provider<br>            android:name=&quot;androidx.startup.InitializationProvider&quot;<br>            android:authorities=&quot;${applicationId}.androidx-startup&quot;<br>            tools:node=&quot;remove&quot;&gt;<br>        &lt;/provider&gt;</pre><p>Voila!! Now you can Read &amp; Upload SMS even when App is not running in Background. WOAH!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*r4SV7HwGT9GShJeD.jpg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b687dcb1bb0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>