Receiving and Sending Application in android Studio
Description:
Receiving and Sending SMS in android- in this article, I am going to show you how to create an application that receives and sends SMS with a full detailed explanation.
Receiving and sending SMS in android:
Sending and receiving text messages should be one of the most basic functions of every mobile phone, even old mobile phones many years ago will have this As an excellent smartphone operating system, Android is naturally indispensable in this aspect. Each Android phone will have a built-in SMS application.
But as a developer, simply being satisfied with this is obviously not enough. You know, Android also provides a series of The listed API allows us to receive and send SMS even in our own applications. In other words, as long as you have enough If you have enough confidence, you can completely implement a text message application yourself to replace the text message application that comes with the Android system. Then down Let’s take a look at how we can receive and send SMS in our own application.
To learn how to develop Kotlin Android applications, you can check out my Kotlin tutorials.
Let us practice it through a specific example.
How to create Receiving and Sending SMS Application in Android Studio:
Receiving SMS in Android Studio:
In fact, receiving SMS mainly uses the broadcast mechanism. When the phone receives a text message At that time, the system will send out a broadcast with a value of android.provider.Telephony.SMS_RECEIVED. In this broadcast Carrying all the data related to SMS. Each application can monitor it in the broadcast receiver, and receive the broadcast The content of the short message can be parsed from it when it is broadcast.
Open android studio and click on a new project
Then select empty activity and click the next button
Then set the application name in my case I set “SendingSmsDemo” and click on the finish button.
As you can see our sending SMS project in fully loaded
Now modify The code in activity_ main.xml as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="From:" /> <TextView android:id="@+id/sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="Content:" /> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> </LinearLayout> |
In this layout file, we placed two LinearLayouts under the root element to display two rows of data.
There are two TextViews in a LinearLayout, which are used to display the sender of the SMS. There is also in the second LinearLayout Two TextView, used to display the content of the short message.
Then modify the code in MainActivity to obtain two instances of TextView in the onCreate() method, such as Shown below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
package com.example.sendingsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); } } |
Then we need to create a broadcast receiver to receive the SMS broadcast from the system. Create a new in MainActivity MessageReceiver inner class inherits from BroadcastReceiver, and write and get the number of short messages in the onReceive() method According to the logic, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
package com.example.sendingsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); } } } |
As you can see, first we took out a Bundle object from the Intent parameter, and then used the pdu key to extract An array of SMS pdus, where each pdu represents an SMS message. Then use SmsMessage The createFromPdu() method converts each pdu byte array into an SmsMessage object, and calls the object’s The getOriginatingAddress() method can obtain the sender number of the SMS, and the getMessageBody() method can be called You can get the content of the SMS, and then splice the content of the SMS in each SmsMessage object to form A complete text message. Finally, the obtained sender number and SMS content are displayed on the TextView. After completing the MessageReceiver, we still need to register it so that it can receive the SMS broadcast. The code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
package com.example.sendingsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); } protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); } } } |
You should be very familiar with these codes, using the technology of dynamically registering broadcasts. On the onCreate() side Register MessageReceiver in the method, and unregister it in the onDestroy() method.
The code is almost completed here, but in the end, we need to declare a right to receive SMS to the program To limit talents, modify the code in AndroidManifest.xml as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sendingsmsdemo"> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.SendingSmsDemo"> <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> |
Now you can run the program, the interface will be shown like the below figure.
As you can see in the below figure our message has been received
Receive SMS on the designed app and block built-in message box:
Carefully observe the above Figure, you will find a notification icon appears in the system status bar, this notification icon is made by Android Generated by the built-in SMS program. In other words, when the text message arrives, not only our program will receive the text message, but the system SMS program will also be received. The same text message received twice will result in a poor user experience, then Is there any way to block the receiving function of the system SMS program?
The short message broadcast sent by the system is an orderly broadcast, so our answer here is yes. Modify the code in MainActivity as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
package com.example.sendingsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsMessage; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); receiveFilter.setPriority(100); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); } protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); abortBroadcast(); } } } |
As you can see all the codes remains the same, but there are only two critical steps are added One is to increase the priority receiveFilter.setPriority(100); of MessageReceiver so that it can Receive SMS broadcast in the system SMS program. The second is to call the abortBroadcast() method in the onReceive() method to abort Continuing delivery if the broadcast is dropped.
Now run the program again and send a text message to the simulator. At this time, only our own program can receive this message Text message. After pressing the Back key to close the program, the system’s SMS program will again have the function of receiving SMS.
Note that this function must be used with caution. Intercepting SMS at will may cause the loss of important data, so you are intercepting Be sure to figure out if this function is what you want before.
Sending SMS in Android Studio:
Let’s continue to expand the SendingSmsDemo project and add the function of sending SMS to it. So let’s write first Take a look at the layout file and modify the code in activity_main.xml as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:layout_marginTop="20dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="From:" /> <TextView android:id="@+id/sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="Content:" /> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="To:" /> <EditText android:id="@+id/to" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <EditText android:id="@+id/msg_input" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Send" /> </LinearLayout> </LinearLayout> |
Here we have added two LinearLayouts, which are in the third and fourth rows respectively. Placed in the third row An EditText, used to enter the recipient’s mobile phone number. An EditText and a Button are placed in the fourth row, They are used to input the content of the short message and send the short message respectively.
Then modify the code in MainActivity to add the processing logic for sending SMS in android, the code is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 |
package com.example.sendingsmsdemo; import androidx.appcompat.app.AppCompatActivity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; private EditText to; private EditText msgInput; private Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(to.getText().toString(), null,msgInput.getText().toString(), null, null); } }); } protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); } } } |
As you can see, first we got the instance of the new control in the layout file, and then clicked on the Send button. The specific logic of sending SMS in android is processed in the file. When the Send button is clicked, the SmsManager will be called first The getDefault() method gets the instance of SmsManager, and then call its sendTextMessage() method.
Go to send a text message. The sendTextMessage() method receives five parameters, of which the first parameter is used to specify the recipient’s hand Phone number, the third parameter is used to specify the content of the message, we don’t use the other parameters temporarily, and directly pass in null That’s it.
Next, you may have guessed that sending SMS in android also requires permission to be declared, so modify AndroidManifest.xml The code in is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sendingsmsdemo"> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.SEND_SMS" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.SendingSmsDemo" > <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> |
If you run the program, SendingSmsDemo has the ability to send SMS. But if you click the Send button, SMS can be sent out, but we don’t know whether the sending is successful or not. here we can add the functionality to monitor the weather SMS sent or not, so Modify the code in MainActivity as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package com.example.sendingsmsdemo; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; private EditText to; private EditText msgInput; private Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED) { MessageSent(); } else { ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},100); } } }); } private void MessageSent() { String phone=to.getText().toString().trim(); String SmsText=msgInput.getText().toString().trim(); if(!phone.equals("") && !SmsText.equals("")) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phone, null,SmsText, null, null); Toast.makeText(getApplicationContext(),"sent",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"fill the fields",Toast.LENGTH_SHORT).show(); } } protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED) { MessageSent(); } else { Toast.makeText(getApplicationContext(),"permission denied",Toast.LENGTH_LONG).show(); } } } |
As you can see, in the click event of the Send button we called the user-defined method MessageSent().
In MessageSent() method I initialize the edit text fields and then set a condition on these fields.
Now run the program again, enter the recipient’s mobile phone number and text message content in the text input box, and then click the Send button, and the result is shown in below Figure.
As you can see our SMS is successfully sent.
Source code of Receiving and Sending SMS in android:
MainActivity.java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 |
package com.example.sendingsmsdemo; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.core.app.ActivityCompat; import androidx.core.content.ContextCompat; import android.Manifest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.PackageManager; import android.os.Bundle; import android.telephony.SmsManager; import android.telephony.SmsMessage; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private TextView sender; private TextView content; private IntentFilter receiveFilter; private MessageReceiver messageReceiver; private EditText to; private EditText msgInput; private Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sender = (TextView) findViewById(R.id.sender); content = (TextView) findViewById(R.id.content); receiveFilter = new IntentFilter(); receiveFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); messageReceiver = new MessageReceiver(); registerReceiver(messageReceiver, receiveFilter); to = (EditText) findViewById(R.id.to); msgInput = (EditText) findViewById(R.id.msg_input); send = (Button) findViewById(R.id.send); send.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.SEND_SMS)== PackageManager.PERMISSION_GRANTED) { MessageSent(); } else { ActivityCompat.requestPermissions(MainActivity.this,new String[]{Manifest.permission.SEND_SMS},100); } } }); } private void MessageSent() { String phone=to.getText().toString().trim(); String SmsText=msgInput.getText().toString().trim(); if(!phone.equals("") && !SmsText.equals("")) { SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage(phone, null,SmsText, null, null); Toast.makeText(getApplicationContext(),"sent",Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(),"fill the fields",Toast.LENGTH_SHORT).show(); } } protected void onDestroy() { super.onDestroy(); unregisterReceiver(messageReceiver); } class MessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Bundle bundle = intent.getExtras(); Object[] pdus = (Object[]) bundle.get("pdus"); // Retrieve SMS messages SmsMessage[] messages = new SmsMessage[pdus.length]; for (int i = 0; i < messages.length; i++) { messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); } String address = messages[0].getOriginatingAddress(); String fullMessage = ""; for (SmsMessage message : messages) { fullMessage += message.getMessageBody(); } sender.setText(address); content.setText(fullMessage); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if(requestCode==100 && grantResults[0]==PackageManager.PERMISSION_GRANTED) { MessageSent(); } else { Toast.makeText(getApplicationContext(),"permission denied",Toast.LENGTH_LONG).show(); } } } |
activity_main.xml code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity" android:layout_marginTop="20dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="From:" /> <TextView android:id="@+id/sender" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="Content:" /> <TextView android:id="@+id/content" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:padding="10dp" android:text="To:" /> <EditText android:id="@+id/to" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="50dp" > <EditText android:id="@+id/msg_input" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:layout_weight="1" /> <Button android:id="@+id/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="Send" /> </LinearLayout> </LinearLayout> |
AndroidManifest.xml code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.sendingsmsdemo"> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.SEND_SMS" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.SendingSmsDemo" > <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> |
Hello Fawad. Good Article.
Do you have the same application code available in Visual Studio Xamarin?
Sorry Mansoor I didn’t work on xamarin. insha Allah, soon I will start it.