How to Delete an SMS in Kotlin

The simplest way to send SMS from Kotlin is to use the built in HTTP/Rest SMS api of Ozeki SMS Gateway. When you use this API, you will send SMS messages by issuing a HTTP Post request to the SMS gateway. The HTTP Post request will contain a message formatted in json format. The SMS gateway will send this SMS to the recipient phone, and it will return a HTTP 200 OK response to your request. (Figure 1)

how to delete an sms in kotlin
Figure 1 - How to Delete an SMS in Kotlin

Kotlin code to delete sms

The Kotlin sms code sample below demonstrates how you can delete SMS message(s) using the http rest sms api of Ozeki SMS Gateway using the Kotlin Ozeki.Libs.Rest library. This library is provided to you free of charge, and you may use it and modify it in any of your projects.

Video 1 - How to download the DeleteSms.kt.zip example (Video tutorial)

MainActivity.kt
package delete.sms

import Ozeki.Libs.Rest.Configuration
import Ozeki.Libs.Rest.Folder
import Ozeki.Libs.Rest.MessageApi
import Ozeki.Libs.Rest.Message
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val folderCategories:android.widget.Spinner = findViewById(R.id.folderCategories)
        val ID:android.widget.EditText = findViewById(R.id.inputId)
        val btnSendRequest:android.widget.Button = findViewById(R.id.btnSendRequest)
        val logBox:android.widget.TextView = findViewById(R.id.logBox)
        logBox.movementMethod = ScrollingMovementMethod()

        val configuration = Configuration(
            username = "http_user",
            password = "qwe123",
            apiurl = "http://10.0.2.2:9509/api"
        )

        val api = MessageApi(configuration)

        btnSendRequest.setOnClickListener {
            if (ID.text.toString() != "") {

                val msg = Message()
                msg.ID = ID.text.toString()

                val folder: Folder

                when (folderCategories.selectedItem.toString()) {
                    "Outbox" -> folder = Folder.Outbox;
                    "Sent" -> folder = Folder.Sent;
                    "Not sent" -> folder = Folder.NotSent;
                    "Deleted" -> folder = Folder.Deleted;
                    else -> folder = Folder.Inbox
                }
                GlobalScope.launch(Dispatchers.IO) {
                    val response = api.Delete(folder, msg)
                    logBox.text = String.format("%s\n%s", logBox.text, response.toString())
                }
                ID.text.clear()
            }
        }
    }
}
	
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textId"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:text="ID:"
        android:textSize="20dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/inputId"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dp"
        android:ems="10"
        android:hint="4c24263b-dacc-48d1-b179-b7e64f08eb26"
        android:inputType="textPersonName"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textId" />

    <Spinner
        android:id="@+id/folderCategories"
        android:layout_width="320dp"
        android:layout_height="50dp"
        android:layout_marginTop="40dp"
        android:entries="@array/folders"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.494"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/inputId" />

    <Button
        android:id="@+id/btnSendRequest"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Delete"
        app:layout_constraintEnd_toEndOf="parent"
        android:backgroundTint="#FF3F3F"
        app:layout_constraintHorizontal_bias="0.505"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/logBox" />

    <TextView
        android:id="@+id/logBox"
        android:layout_width="320dp"
        android:layout_height="250dp"
        android:layout_marginTop="40dp"
        android:scrollbars="vertical"
        android:text="Logs:"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/folderCategories" />
</androidx.constraintlayout.widget.ConstraintLayout>
	

How to use the Kotlin sms example:

You can use the MessageApi class to delete SMS message(s) from the SMS gateway. You request will be forwarded to the SMS Gateway from your device through internet.

Download DeleteSms.kt

The source code explained in this article can be downloaded and used and modified free of charge.
Download: DeleteSms.kt.zip (149Kb)

What is in the DeleteSms.kt.zip file?

The DeleteSms.kt.zip file contains the an example project, which has the Ozeki.Libs.Rest library in it. With this library you can send, delete, mark and receive sms messages by creating a MessageApi and using the Send(), Delete(), Mark(), and Receive() methods. (Figure 2)

example project to delete sms using kotlin
Figure 2 - DeleteSms.kt directory

How to delete SMS with Kotlin (Quick steps)

To delete sms with Kotlin:

  1. Install Ozeki SMS Gateway
  2. Connect Ozeki SMS Gateway to the mobile network
  3. Send a test sms from Ozeki GUI
  4. Create a HTTP sms api user
  5. Android Studio
  6. Download the example project above
  7. Create the SMS by creating a new Message object
  8. Create an api to delete an SMS message
  9. Use the Delete method to delete your message
  10. Read the response message on the console
  11. Check the logs in the SMS gateway

Install Ozeki SMS Gateway and create an HTTP API user

To be able to delete SMS with Kotlin, first you need to install Ozeki SMS Gateway. The SMS gateway can be installed on the same computer, where you develop your Kotlin code in Android Studio. After installation, the next step is to connect Ozeki SMS Gateway to the mobile network. You can send a test sms from the Ozeki GUI to verify, that your mobile network connection works. The final step to prepare your environment is to create a HTTP sms api user. Create a user with a username of "http_user", and with a password of "qwe123" to make the example work without modification.

After the environment is setup, you can run your Kotlin code.

HTTP API url to use send sms from Kotlin

To delete SMS with Kotlin, your Kotlin will have to issue an HTTP request to the SMS gateway. The API url is shown below. Note that the IP address (127.0.0.1) should be replaced to the IP address of your SMS gateway. If Ozeki SMS Gateway is installed on the same computer where the JavaScript sms application is running, this can be 127.0.0.1. If it is installed on a different computer, it should be the IP address of that computer.

http://127.0.0.1:9509/api?action=rest
	

HTTP authentication to use delete sms with Kotlin

To authenticate the Kotlin sms client, you need to send the username and password in a base64 encoded string to the server in a HTTP request. The format used is: base64(username+":"+password). In Kotlin you can use the following code to do this encoding:

var usernamePassword = "%s:%s".format(username, password)
return "Basic %s".format(Base64.getEncoder().encodeToString(usernamePassword.toByteArray()))
	

For example if you encode the username 'http_user' and the password 'qwe123', you will get the following base64 encoded string: aHR0cF91c2VyOnF3ZTEyMw==. To send

HTTP request header to delete SMS from Kotlin

To delete the SMS message(s), you need to include the following lines as headers in the HTTP request. Note that we include a content type and an Authorization header.

Content-Type: application/json
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
	

HTTP request to receive SMS with Kotlin

To delete SMS, your Kotlin application will send an HTTP request similar to the one below. Note, that this requst contains a HTTP header part and a http body part. The HTTP body is a JSON encoded data string. It contains the IDs of the messages you want to delete.

POST /api?action=deletemsg HTTP/1.1
Connection: Keep-Alive
Content-Length: 73
Content-Type: application/json; charset=utf-8
Accept-Encoding: gzip
Authorization: Basic aHR0cF91c2VyOnF3ZTEyMw==
Host: 10.0.2.2:9509
User-Agent: okhttp/4.2.2

{
	"folder":	"inbox",
	"message_ids":	[
		"f07b71e9-6c4c-8ff1-88a5-3aa9fec74966"
	]
}
	

HTTP response received by the Kotlin sms example

Once the SMS gateway receives this request, it will generate a HTTP response. The HTTP response will contain a status code, to indicate whether the SMS submit request was successful or not. It will also return a JSON encoded structure to provide you useful details about the message's submission.

HTTP/1.1 200 OK
User-Agent: OZEKI 10.3.120 (www.myozeki.com)
Content-Type: application/json; charset=utf8
Last-Modified: Fri, 18 Jun 2021 08:10:45 GMT
Server: 10/10.3.120
Transfer-Encoding: chunked

{
	"http_code": 200,
	"response_code": "SUCCESS",
	"response_msg": "",
	"data": {
	  "folder": "inbox",
	  "message_ids": [
	    "f07b71e9-6c4c-8ff1-88a5-3aa9fec74966"
	  ]
	}
}
	

How to delete SMS messages with Kotlin using the sms api and the example project above (Video tutorial)

This video shows you how to download and use the DeleteSms.kt project. Once you opened the example project, you might notice that a there is a package called Ozeki.Libs.Rest This is the package that contains the MessageApi and all the stuffs you need to delete SMS message(s) using Kotlin.

Video 2 - How to delete SMS with the Kotlin code above (Video tutorial)

How to check that the request has been accepted by the HTTP user

After the SMS has been submitted, it is a good idea to check your SMS gateway, to see what it has received. You can check the log by opening the HTTP user's details from the Ozeki SMS Gateway management console. At the end of the video above you can see how to check if the request has been received by the http_user. (Figure 3)

kotlin project to receive sms messages
Figure 3 - DeleteSms.kt project in Android Studio

Using the app on a phone

On Figure 4, you can see how deleting an SMS message looks like when you are using the application on a phone. Paste the message ID into the 'ID' textbox and press the 'Delete' button. It will delete the chosen message. If the process were successfully done, you will see the 'true' message in the 'Logs' section.

example kotlin application to receive sms messages
Figure 4 - DeleteSms example application before and after the messages have been downloaded

How to add Ozeki.Libs.Rest to your own project

The Ozeki.Libs.Rest library can be downloaded and used and modified free of charge.
Download: Ozeki.Libs.Rest.kt.zip (7.66Kb)

If you decide to create your application on your own only with the Ozeki.Libs.Rest library, there are few things you should change in your base application. In order to use the Ozeki.Libs.Rest library you have to put it into the java folder of the main directory
In the following video I will show you how to download and add the Ozeki.Libs.Rest library to your own project.

Video 3 - How to add the Ozeki.Libs.Rest library to your own application (Video tutorial)

Dependencies

It is important to mention, that the Ozeki.Libs.Rest library has some dependencies. In order to use it you have to add these dependencies into the Gradle Scripts.

implementation "com.squareup.okhttp3:okhttp:4.2.2"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.0'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.0'
	

Code 1 - The list of the dependencies you need to include.

How to add the needed dependencies (Video tutorial)

In this video, we are presenting you with the process of adding dependencies to your project. The video will start with copying the code from this tutorial page and will end with the dependencies in the project. These dependencies are crucial parts of the project. Without these, the Ozeki.Libs.Rest will not work. This video is only 53 seconds, but it is easy to understand and follow.

Video 4 - How to add the needed dependencies (Video tutorial)

Internet access

In order to make it possible for your application to send an HTTP request, you have to enable your application to connect to the internet.
In the following video I'll show you how to enable internet access for your Kotlin application.

<uses-permission android:name="android.permission.INTERNET" />
	

Code 2 - To enable internet access for your Kotlin application.

android:usesCleartextTraffic="true"
	

Code 3 - To make it able to send http requests

How to add internet connection to your project (Video tutorial)

You need to add both of these lines to the AndroidManifest.xml file.
In the next video, I'll show you where you should enter the codes earlier. The video will start with copying the code and will take you to the successfully added internet connection. This video is accurate and easy to follow.

Video 5 - How to allow internet access for your application (Video tutorial)

Final thoughts

This article tells you how to use the given Kotlin code to delete SMS messages with the HTTP user of the Ozeki SMS Gateway. If you have to deal with many SMS messages day by day and several of them are unwanted, the procedure shown here is essential for you. A frequently cleared therefore balanced storage is very important in all areas, it allows for more dynamic, efficient work.

Continue this instructive journey on the Ozeki webpage, choose from the many other articles. Let's read the article titled Github: Koltin SMS API, it is about one of the repositories you can use freely.

Download the Ozeki SMS Gateway now and use what you have learned!

More information