Send and receive SMS messages using your Android phone programmatically via a simple HTTP API
Add HttpSmsApiService
Acho Arnold6c1b347d1978
diff --git a/android/app/build.gradle b/android/app/build.gradleindex 7fef7783..6cc7f034 100644--- a/android/app/build.gradle+++ b/android/app/build.gradle@@ -1,11 +1,14 @@plugins {id 'com.android.application'id 'org.jetbrains.kotlin.android'+ id 'com.google.gms.google-services'}android {compileSdk 32+ buildToolsVersion "32.0.0"+defaultConfig {applicationId "com.httpsms"minSdk 30@@ -32,8 +35,15 @@ android {}dependencies {+ implementation platform('com.google.firebase:firebase-bom:30.1.0')+ implementation 'com.google.firebase:firebase-analytics-ktx'+ implementation 'com.google.firebase:firebase-messaging-ktx'+ implementation 'com.squareup.okhttp3:okhttp:4.10.0'+ implementation 'androidx.work:work-runtime-ktx:2.7.1'implementation 'androidx.core:core-ktx:1.8.0'implementation "androidx.cardview:cardview:1.0.0"+ implementation 'com.beust:klaxon:5.5'+ implementation 'androidx.work:work-runtime-ktx:2.7.1'implementation 'androidx.appcompat:appcompat:1.4.2'implementation 'com.google.android.material:material:1.6.1'implementation 'androidx.constraintlayout:constraintlayout:2.1.4'diff --git a/android/app/google-services.json b/android/app/google-services.jsonnew file mode 100644index 00000000..4db4c064--- /dev/null+++ b/android/app/google-services.json@@ -0,0 +1,47 @@+{+ "project_info": {+ "project_number": "877524083399",+ "project_id": "httpsms-86c51",+ "storage_bucket": "httpsms-86c51.appspot.com"+ },+ "client": [+ {+ "client_info": {+ "mobilesdk_app_id": "1:877524083399:android:5ceb08a909fd24a96514e2",+ "android_client_info": {+ "package_name": "com.httpsms"+ }+ },+ "oauth_client": [+ {+ "client_id": "877524083399-londfmd80qqlb2gebpbhctavlmqtla3b.apps.googleusercontent.com",+ "client_type": 1,+ "android_info": {+ "package_name": "com.httpsms",+ "certificate_hash": "58df9f7489b8bb5e3cd57f01a03d5e0068d8c185"+ }+ },+ {+ "client_id": "877524083399-7pn57hd8k2js6tc93i428ko1m51mj50r.apps.googleusercontent.com",+ "client_type": 3+ }+ ],+ "api_key": [+ {+ "current_key": "AIzaSyBKiokmk5qhE2Zc5F97KWzOvRe8FDDuxDg"+ }+ ],+ "services": {+ "appinvite_service": {+ "other_platform_oauth_client": [+ {+ "client_id": "877524083399-7pn57hd8k2js6tc93i428ko1m51mj50r.apps.googleusercontent.com",+ "client_type": 3+ }+ ]+ }+ }+ }+ ],+ "configuration_version": "1"+}diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex 9e711bb7..c930807d 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -1,33 +1,48 @@-<?xml version="1.0" encoding="utf-8"?>-<manifest xmlns:android="http://schemas.android.com/apk/res/android"- xmlns:tools="http://schemas.android.com/tools"- package="com.httpsms">--- <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />- <uses-permission android:name="android.permission.READ_PHONE_STATE" />- <uses-permission android:name="android.permission.READ_SMS" />- <uses-permission android:name="android.permission.SEND_SMS" />-- <application- android:allowBackup="true"- android:dataExtractionRules="@xml/data_extraction_rules"- android:fullBackupContent="@xml/backup_rules"- android:icon="@mipmap/ic_launcher"- android:label="@string/app_name"- android:roundIcon="@mipmap/ic_launcher_round"- android:supportsRtl="true"- android:theme="@style/Theme.HttpSMS"- tools:targetApi="31">- <activity- android:name=".MainActivity"- android:exported="true">- <intent-filter>- <action android:name="android.intent.action.MAIN" />-- <category android:name="android.intent.category.LAUNCHER" />- </intent-filter>- </activity>- </application>--</manifest>+<?xml version="1.0" encoding="utf-8"?>+<manifest xmlns:android="http://schemas.android.com/apk/res/android"+ xmlns:tools="http://schemas.android.com/tools"+ package="com.httpsms">+++ <uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />+ <uses-permission android:name="android.permission.READ_PHONE_STATE" />+ <uses-permission android:name="android.permission.READ_SMS" />+ <uses-permission android:name="android.permission.SEND_SMS" />+ <uses-permission android:name="android.permission.RECEIVE_SMS" />+ <uses-permission android:name="android.permission.INTERNET" />+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />+++ <application+ android:allowBackup="true"+ android:dataExtractionRules="@xml/data_extraction_rules"+ android:fullBackupContent="@xml/backup_rules"+ android:icon="@mipmap/ic_launcher"+ android:label="@string/app_name"+ android:roundIcon="@mipmap/ic_launcher_round"+ android:supportsRtl="true"+ android:theme="@style/Theme.HttpSMS"+ tools:targetApi="31">+ <activity+ android:name=".MainActivity"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.MAIN" />++ <category android:name="android.intent.category.LAUNCHER" />+ </intent-filter>+ </activity>++ <service+ android:name=".MyFirebaseMessagingService"+ android:exported="false">+ <intent-filter>+ <action android:name="com.google.firebase.MESSAGING_EVENT" />+ </intent-filter>+ </service>++ <meta-data+ android:name="com.google.firebase.messaging.default_notification_channel_id"+ android:value="com.httpsms.notification.default" />+ </application>+</manifest>diff --git a/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.ktnew file mode 100644index 00000000..47749593--- /dev/null+++ b/android/app/src/main/java/com/httpsms/FirebaseMessagingService.kt@@ -0,0 +1,80 @@+package com.httpsms++import android.content.Context+import android.util.Log+import androidx.work.OneTimeWorkRequest+import androidx.work.WorkManager+import androidx.work.Worker+import androidx.work.WorkerParameters+import com.google.firebase.messaging.FirebaseMessagingService+import com.google.firebase.messaging.RemoteMessage++class MyFirebaseMessagingService : FirebaseMessagingService() {++ // [START receive_message]+ override fun onMessageReceived(remoteMessage: RemoteMessage) {+ // TODO(developer): Handle FCM messages here.+ // Not getting messages here? See why this may be: https://goo.gl/39bRNJ+ Log.d(TAG, "From: ${remoteMessage.from}")++ scheduleJob()++ // Check if message contains a notification payload.+ remoteMessage.notification?.let {+ Log.d(TAG, "Message Notification Body: ${it.body}")+ }++ // Also if you intend on generating your own notifications as a result of a received FCM+ // message, here is where that should be initiated. See sendNotification method below.+ }+ // [END receive_message]++ // [START on_new_token]+ /**+ * Called if the FCM registration token is updated. This may occur if the security of+ * the previous token had been compromised. Note that this is called when the+ * FCM registration token is initially generated so this is where you would retrieve the token.+ */+ override fun onNewToken(token: String) {+ Log.d(TAG, "Refreshed token: $token")++ // If you want to send messages to this application instance or+ // manage this apps subscriptions on the server side, send the+ // FCM registration token to your app server.+ sendRegistrationToServer(token)+ }+ // [END on_new_token]++ private fun scheduleJob() {+ // [START dispatch_job]+ val work = OneTimeWorkRequest+ .Builder(SendSmsWorker::class.java)+ .build()++ WorkManager+ .getInstance(this)+ .enqueue(work)+ // [END dispatch_job]+ }+ private fun sendRegistrationToServer(token: String?) {+ // TODO: Implement this method to send token to your app server.+ Log.d(TAG, "sendRegistrationTokenToServer($token)")+ }++ companion object {+ private val TAG = MyFirebaseMessagingService::class.simpleName+ }++ internal class SendSmsWorker(appContext: Context, workerParams: WorkerParameters) : Worker(appContext, workerParams) {+ override fun doWork(): Result {+ Log.i(TAG, "fetching messages")+ val smsService = SmsManagerService()+ val messages = HttpSmsApiService().getOutstandingMessages()+ messages.forEach {+ message -> smsService.SendMessage(this.applicationContext, message, null, null)+ }+ Log.i(TAG, "received [${messages.size}] messages")+ return Result.success()+ }+ }+}diff --git a/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt b/android/app/src/main/java/com/httpsms/HttpSmsApiService.ktnew file mode 100644index 00000000..c7abbc6b--- /dev/null+++ b/android/app/src/main/java/com/httpsms/HttpSmsApiService.kt@@ -0,0 +1,36 @@+package com.httpsms++import android.util.Log+import okhttp3.OkHttpClient+import okhttp3.Request;+import java.net.URI+++class HttpSmsApiService {+ private val baseURL = URI("https://httpsms.free.beeceptor.com")++ fun getOutstandingMessages(): List<Message> {+ val client = OkHttpClient()++ val request: Request = Request.Builder()+ .url(baseURL.resolve("/v1/messages/outstanding").toURL())+ .build()++ val response = client.newCall(request).execute()+ if (response.isSuccessful) {+ val payload = MessagesOutstanding.fromJson(response.body!!.string())?.data+ if (payload == null) {+ Log.e(TAG, "cannot decode payload [${response.body}]")+ return listOf();+ }+ return payload+ }++ Log.e(TAG, "invalid response with code [${response.code}] and payload [${response.body}]")+ return listOf()+ }++ companion object {+ private val TAG = HttpSmsApiService::class.simpleName+ }+}diff --git a/android/app/src/main/java/com/httpsms/MainActivity.kt b/android/app/src/main/java/com/httpsms/MainActivity.ktindex 1338c179..215d9e6a 100644--- a/android/app/src/main/java/com/httpsms/MainActivity.kt+++ b/android/app/src/main/java/com/httpsms/MainActivity.kt@@ -15,6 +15,7 @@ import android.widget.Toastimport androidx.activity.result.contract.ActivityResultContractsimport androidx.appcompat.app.AppCompatActivityimport androidx.core.app.ActivityCompat+import androidx.core.content.ContextCompatimport java.util.*@@ -60,6 +61,13 @@ class MainActivity : AppCompatActivity() {) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.READ_PHONE_STATE+ ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(+ this,+ Manifest.permission.SEND_SMS+ ) != PackageManager.PERMISSION_GRANTED+ && ActivityCompat.checkSelfPermission(+ this,+ Manifest.permission.RECEIVE_SMS) != PackageManager.PERMISSION_GRANTED) {// You can directly ask for the permission.@@ -67,10 +75,14 @@ class MainActivity : AppCompatActivity() {requestPermissionLauncher.launch(Manifest.permission.READ_SMS)requestPermissionLauncher.launch(Manifest.permission.READ_PHONE_NUMBERS)requestPermissionLauncher.launch(Manifest.permission.READ_PHONE_STATE)+ requestPermissionLauncher.launch(Manifest.permission.SEND_SMS)+ requestPermissionLauncher.launch(Manifest.permission.RECEIVE_SMS)+}val phoneNumber = telephonyManager.line1Number ?: "NO_PHONE_NUMBER"Log.d(logTag, phoneNumber)return phoneNumber}+}diff --git a/android/app/src/main/java/com/httpsms/Models.kt b/android/app/src/main/java/com/httpsms/Models.ktnew file mode 100644index 00000000..aa884c35--- /dev/null+++ b/android/app/src/main/java/com/httpsms/Models.kt@@ -0,0 +1,59 @@+// To parse the JSON, install Klaxon and do:+//+// val welcome4 = Welcome4.fromJson(jsonString)++package com.httpsms++import com.beust.klaxon.*++private val klaxon = Klaxon()++data class MessagesOutstanding (+ val data: List<Message>,+ val message: String,+ val status: String+) {+ public fun toJson() = klaxon.toJsonString(this)+ companion object {+ public fun fromJson(json: String) = klaxon.parse<MessagesOutstanding>(json)+ }+}++data class Message (+ val contact: String,+ val content: String,++ @Json(name = "created_at")+ val createdAt: String,++ @Json(name = "failure_reason")+ val failureReason: String,++ val id: String,++ @Json(name = "last_attempted_at")+ val lastAttemptedAt: String,++ @Json(name = "order_timestamp")+ val orderTimestamp: String,++ val owner: String,++ @Json(name = "received_at")+ val receivedAt: String,++ @Json(name = "request_received_at")+ val requestReceivedAt: String,++ @Json(name = "send_time")+ val sendTime: Long,++ @Json(name = "sent_at")+ val sentAt: String,++ val status: String,+ val type: String,++ @Json(name = "updated_at")+ val updatedAt: String+)diff --git a/android/app/src/main/java/com/httpsms/SmsManagerService.kt b/android/app/src/main/java/com/httpsms/SmsManagerService.ktnew file mode 100644index 00000000..f83f2b56--- /dev/null+++ b/android/app/src/main/java/com/httpsms/SmsManagerService.kt@@ -0,0 +1,12 @@+package com.httpsms++import android.app.PendingIntent+import android.content.Context+import android.telephony.SmsManager++class SmsManagerService {+ fun SendMessage(context: Context, message: Message, sentIntent:PendingIntent, deliveryIntent: PendingIntent) {+ val smsManager: SmsManager = context.getSystemService(SmsManager::class.java)+ smsManager.sendTextMessage(message.contact, message.owner, message.content, sentIntent, deliveryIntent)+ }+}diff --git a/android/build.gradle b/android/build.gradleindex cc8f2456..02d2a8bb 100644--- a/android/build.gradle+++ b/android/build.gradle@@ -1,4 +1,16 @@// Top-level build file where you can add configuration options common to all sub-projects/modules.+buildscript {+ repositories {+ // Check that you have the following line (if not, add it):+ google() // Google's Maven repository++ }+ dependencies {+ // Add this line+ classpath 'com.google.gms:google-services:4.3.12'+ }+}+plugins {id 'com.android.application' version '7.2.1' apply falseid 'com.android.library' version '7.2.1' apply false