How to Read Sms Permission in Android Studio
2.one - Part 1: Sending and Receiving SMS Messages
Contents:
- What you should already KNOW
- What you will Learn
- What yous will DO
- App overview
- Job ane: Launch a messaging app to send a message
- Job 2: Transport an SMS message from within an app
Android smartphones can transport and receive messages to or from any other phone that supports Short Message Service (SMS). Y'all have two choices for sending SMS messages:
- Use an implicit Intent to launch a messaging app with the ACTION_SENDTO intent action.
- This is the simplest selection for sending letters. The user can add a pic or other attachment in the messaging app, if the messaging app supports adding attachments.
- Your app doesn't demand lawmaking to request permission from the user.
- If the user has multiple SMS messaging apps installed on the Android phone, the App chooser will announced with a listing of these apps, and the user tin choose which i to use. (Android smartphones volition have at least 1, such as Messenger.)
- The user can change the message in the messaging app earlier sending it.
- The user navigates dorsum to your app using the Dorsum push button.
- Send the SMS message using the sendTextMessage() method or other methods of the SmsManager course.
- This is a expert option for sending letters from your app without having to use another installed app.
- Your app must ask the user for permission earlier sending the SMS message, if the user hasn't already granted permission.
- The user stays in your app during and after sending the message.
- You can manage SMS operations such as dividing a message into fragments, sending a multipart message, get carrier-dependent configuration values, and so on.
To receive SMS letters, use the onReceive() method of the BroadcastReceiver grade.
What you lot should already KNOW
Y'all should already be able to:
- Create an onClick method for a button with the
android:onClick
attribute. - Use an implicit intent to perform a role with some other app.
- Utilise a broadcast receiver to receive system events.
What yous volition LEARN
In this applied, you will learn to:
- Launch an SMS messaging app from your app with a phone number and message.
- Send an SMS bulletin from within an app.
- Check for the SMS permission, and request permission if necessary.
- Receive SMS events using a broadcast receiver.
- Excerpt an SMS bulletin from an SMS result.
What you will DO
In this applied, you will:
- Create an app that uses an implicit intent to launch a messaging app.
- Laissez passer data (the phone number) and the message with the implicit intent.
- Create an app that sends SMS letters using the SmsManager class.
- Check for the SMS permission, which tin can change at any time.
- Asking permission from the user, if necessary, to ship SMS letters.
- Receive and process an SMS message.
App overview
You volition create ii new apps based on apps you created previously for the lesson about making telephone calls:
-
PhoneMessaging: Rename and refactor the PhoneCallDial app from the previous chapter, and add lawmaking to enable a user to not just dial a difficult-coded telephone number but also ship an SMS message to the telephone number. It uses an implicit intent using
ACTION_SENDTO
and the telephone number to launch a messaging app to transport the message.As shown in the figure below, the PhoneCallDial app already has TextEdit views for the contact name and the hard-coded phone number, and an ImageButton for making a phone call. You will re-create the app, rename information technology to PhoneMessaging, and alter the layout to include an EditText for entering the bulletin, and another ImageButton with an icon that the user can tap to transport the message.
-
SMS Messaging: Change the PhoneCallingSample app from the previous affiliate to enable a user to enter a phone number, enter an SMS message, and send the message from within the app. It checks for permission then uses the SmsManager class to send the message.
As shown in the figure below, the PhoneCallingSample app already has an EditText view for inbound the phone number and an ImageButton for making a phone call. Y'all will copy the app, rename it to SmsMessaging, and change the layout to include another EditText for inbound the message, and change the ImageButton to an icon that the user can tap to send the bulletin.
Task 1. Launch a messaging app to ship a message
In this task you lot create an app called PhoneMessaging, a new version of the PhoneCallDial app from a previous lesson. The new app launches a messaging app with an implicit intent, and passes a fixed phone number and a message entered by the user.
The user tin can tap the messaging icon in your app to send the message. In the messaging app launched past the intent, the user can tap to transport the bulletin, or change the bulletin or the phone number before sending the message. After sending the message, the user can navigate back to your app using the Back button.
1.1 Modify the app and layout
- Copy the PhoneCallDial project binder, rename it to PhoneMessaging, and refactor it to populate the new name throughout the app project. (Meet the Appendix for instructions on copying a projection.)
-
Add an icon for the messaging push button by following these steps:
-
Select drawable in the Project: Android view and choose File > New > Vector Asset.
-
Click the Android icon next to "Icon:" to choose an icon. To find a messaging icon, cull Communication in the left column.
-
Select the icon, click OK, click Next, and then click Finish.
-
-
Add the following EditText to the existing layout after the
phone_icon
ImageButton:... <ImageButton android:id="@+id/phone_icon" ... /> <EditText android:id="@+id/sms_message" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_below="@id/number_to_call" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_marginRight="@dimen/activity_horizontal_margin" android:hint="Enter message here" android:inputType="textMultiLine"/>
You will apply the
android:id
sms_message
to call back the message in your code. You can employ@dimen/activity_horizontal_margin
and@dimen/activity_vertical_margin
for the EditText margins because they are already defined in the dimens.xml file. The EditText view uses theandroid:inputType
attribute set to"textMultiLine"
for inbound multiple lines of text. - After adding hard-coded strings and dimensions, excerpt them into resources:
-
android:layout_width="@dimen/edittext_width"
: The width of the EditText bulletin (200dp). -
android:hint="@string/enter_message_here"
: The hint for the EditText ("Enter message here").
-
-
Add the post-obit ImageButton to the layout after the above EditText:
<ImageButton android:id="@+id/message_icon" android:contentDescription="Transport a bulletin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_toRightOf="@id/sms_message" android:layout_toEndOf="@id/sms_message" android:layout_below="@id/phone_icon" android:src="@drawable/ic_message_black_24dp" android:onClick="smsSendMessage"/>
Yous volition use the
android:id
message_icon
to refer to the ImageButton for launching the messaging app. Apply the vector asset you added previously (such asic_message_black_24dp
for a messaging icon) for the ImageButton. -
Afterwards adding the hard-coded string for the
android:contentDescription
attribute, extract it into the resourcessend_a_message
.The
smsSendMessage()
method referred to in theandroid:onClick
attribute remains highlighted until you create this method in the MainActivity, which you will do in the side by side step. -
Click
smsSendMessage
in theandroid:onClick
attribute, click the red light seedling that appears, and then select Create smsSendMessage(View) in 'MainActivity'. Android Studio automatically creates thesmsSendMessage()
method in MainActivity aspublic
, returningvoid
, with aView
parameter. This method is called when the user taps themessage_icon
ImageButton.public void smsSendMessage(View view) { }
Your app'south layout should at present wait like the following figure:
one.ii Edit the onClick method in MainActivity
- Inside the
smsSendMessage()
method in MainActivity, become the phone number from thenumber_to_call
TextView, and concatenate it with thesmsto:
prefix (as insmsto:14155551212
) to create the phone number URI cordsmsNumber
:... TextView textView = (TextView) findViewById(R.id.number_to_call); // Employ format with "smsto:" and telephone number to create smsNumber. String smsNumber = String.format("smsto: %s", textView.getText().toString()); ...
- Become the string of the message entered into the EditText view:
... // Find the sms_message view. EditText smsEditText = (EditText) findViewById(R.id.sms_message); // Become the text of the SMS bulletin. String sms = smsEditText.getText().toString(); ...
-
Create an implicit intent (
smsIntent
) with the intent actionACTION_SENDTO
, and set the phone number and text message equally intent information and extended data, usingsetData()
andputExtra
:... // Create the intent. Intent smsIntent = new Intent(Intent.ACTION_SENDTO); // Prepare the data for the intent every bit the phone number. smsIntent.setData(Uri.parse(smsNumber)); // Add the bulletin (sms) with the key ("sms_body"). smsIntent.putExtra("sms_body", sms); ...
The putExtra() method needs two strings: the primal identifying the type of data (
"sms_body"
) and the data itself, which is the text of the message (sms
). For more information virtually common intents and theputExtra()
method, see Common Intents: Text Messaging. -
Add together a check to encounter if the implicit intent resolves to a package (a messaging app). If information technology does, send the intent with
startActivity()
, and the organisation launches the app. If it does not, log an error.... // If parcel resolves (target app installed), send intent. if (smsIntent.resolveActivity(getPackageManager()) != naught) { startActivity(smsIntent); } else { Log.e(TAG, "Can't resolve app for ACTION_SENDTO Intent"); } ...
The total method should now look like the following:
public void smsSendMessage(View view) { TextView textView = (TextView) findViewById(R.id.number_to_call); // Use format with "smsto:" and phone number to create smsNumber. String smsNumber = String.format("smsto: %s", textView.getText().toString()); // Detect the sms_message view. EditText smsEditText = (EditText) findViewById(R.id.sms_message); // Get the text of the sms bulletin. String sms = smsEditText.getText().toString(); // Create the intent. Intent smsIntent = new Intent(Intent.ACTION_SENDTO); // Set the data for the intent as the phone number. smsIntent.setData(Uri.parse(smsNumber)); // Add together the message (sms) with the cardinal ("sms_body"). smsIntent.putExtra("sms_body", sms); // If package resolves (target app installed), send intent. if (smsIntent.resolveActivity(getPackageManager()) != nil) { startActivity(smsIntent); } else { Log.d(TAG, "Can't resolve app for ACTION_SENDTO Intent"); } }
i.three Run the app
- Run the app on either an emulator or a device.
-
Enter a message, and tap the messaging icon (marked "one" in the left side of the figure beneath). The messaging app appears, as shown on the correct side of the effigy beneath.
- Employ the Back push to return to the PhoneMessaging app. You may demand to tap or click it more than one time to get out the SMS messaging app.
Solution lawmaking
Android Studio project: PhoneMessaging
Task ii. Send an SMS bulletin from within an app
In this task you will copy the PhoneCallingSample app from the lesson on making a phone telephone call, rename and refactor it to SmsMessaging, and alter its layout and code to create an app that enables a user to enter a phone number, enter an SMS message, and transport the message from within the app.
In the starting time step y'all volition add the code to send the message, but the app will work only if you commencement plow on SMS permission manually for the app in Settings on your device or emulator.
In subsequent steps you will practice away with setting this permission manually by requesting SMS permission from the app's user if it is not already set.
two.1 Create the app and layout and add permission
- Re-create the PhoneCallingSample project folder, rename it to SmsMessaging, and refactor it to populate the new name throughout the app project. (See the Appendix for instructions on copying a project.)
- Open strings.xml and change the
app_name
string resource to"SMS Messaging"
. -
Add the
android.permission.SEND_SMS
permission to the AndroidManifest.xml file, and remove theCALL_PHONE
andREAD_PHONE_STATE
permissions for phone use, so that yous have but one permission:<uses-permission android:proper noun="android.permission.SEND_SMS" />
Sending an SMS message is permission-protected. Your app tin't use SMS without the
SEND_SMS
permission line in AndroidManifest.xml. This permission line enables a setting for the app in the Settings app that gives the user the choice of assuasive or disallowing apply of SMS. (In the adjacent task you will add a manner for the user to grant that permission from within the app.) - Add a messaging icon as yous did in the previous task, and remove the phone icon from the drawable folder.
- Open activity_main.xml and edit the EditText view and replace the
android:layout_margin
aspect with the following:... android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_marginRight="@dimen/activity_horizontal_margin" ...
@dimen/activity_horizontal_margin
and@dimen/activity_vertical_margin
considering they are already defined in the dimens.xml file. -
Add the post-obit EditText to the layout after the first EditText (for an paradigm of the layout, see the figure at the cease of these steps):
... <EditText android:id="@+id/sms_message" android:layout_width="@dimen/edittext_width" android:layout_height="wrap_content" android:layout_below="@id/editText_main" android:layout_margin="@dimen/activity_horizontal_margin" android:hint="Enter bulletin here" android:inputType="textMultiLine"/>
You will utilize the
android:id
aspect tosms_message
to identify it equally the EditText for the bulletin. The EditText view uses theandroid:inputType
attribute fix to"textMultiLine"
for inbound multiple lines of text. -
Afterwards adding the hard-coded string "Enter message here" for the
android:hint
attribute, extract information technology into the text resources"enter_message_here"
. -
Change the
android:layout_below
aspect for thebutton_retry
Button to refer to thesms_message
EditText view. The Button should appear below the SMS bulletin in the layout if it becomes visible:android:layout_below="@id/sms_message"
The
button_retry
Button is set to invisible. Information technology appears but if the app detected that telephony is not enabled, or if the user previously denied phone permission when the app requested information technology. -
Supervene upon the
phone_icon
ImageButton from the existing layout with the following:<ImageButton android:id="@+id/message_icon" android:contentDescription="Send a bulletin" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_toRightOf="@id/sms_message" android:layout_toEndOf="@id/sms_message" android:layout_below="@id/editText_main" android:src="@drawable/ic_message_black_24dp" android:visibility="visible" android:onClick="smsSendMessage"/>
Y'all will use the
android:id
message_icon
in your code to refer to the ImageButton for sending the message. Use the vector asset you added previously (such asic_message_black_24dp
for a messaging icon) for the ImageButton. Make sure you include theandroid:visibility
attribute set to"visible"
. You will control the visibility of this ImageButton from your code. -
After adding a hard-coded cord for the
android:contentDescription
aspect, extract it to thesend_a_message
cord resource.The
smsSendMessage()
method referred to in theandroid:onClick
attribute for the ImageButton remains highlighted until you create this method in the MainActivity, which you will do in the adjacent footstep. -
Click
smsSendMessage
in theandroid:onClick
aspect, click the ruddy light bulb that appears, and and so select Create smsSendMessage(View) in 'MainActivity'. Android Studio automatically creates thesmsSendMessage()
method in MainActivity every bitpublic
, returningvoid
, with aView
parameter. This method is chosen when the user taps themessage_icon
ImageButton.public void smsSendMessage(View view) { }
Your app's layout should look similar the following figure (the button_retry
Button is invisible):
2.two Edit the onClick method in MainActivity
- Open MainActivity and find the new
smsSendMessage()
method y'all created in the last stride. - Add together statements to the method to get the string for the phone number from the
editText_main
view, and get the string for the SMS message from thesms_message
view:public void smsSendMessage(View view) { EditText editText = (EditText) findViewById(R.id.editText_main); // Set the destination phone number to the string in editText. String destinationAddress = editText.getText().toString(); // Detect the sms_message view. EditText smsEditText = (EditText) findViewById(R.id.sms_message); // Go the text of the sms message. String smsMessage = smsEditText.getText().toString(); ... }
- Declare additional string and
PendingIntent
parameters for the sendTextMessage() method, which will send the bulletin (destinationAddress
is already declared as the string for the telephone number to receive the message):-
scAddress
: A string for the service heart address, ornada
to use the current default SMSC. A Curt Bulletin Service Middle (SMSC) is a network chemical element in the mobile telephone network. The mobile network operator usually presets the correct service centre number in the default contour of settings stored in the device's SIM carte du jour. -
smsMessage
: A string for the body of the message to transport. -
sentIntent
: APendingIntent
. If notnull
, this is broadcast when the message is successfully sent or if the message failed. -
deliveryIntent
: APendingIntent
. If nonnull
, this is broadcast when the message is delivered to the recipient.... // Set the service center accost if needed, otherwise zip. String scAddress = null; // Set up pending intents to broadcast // when message sent and when delivered, or set to null. PendingIntent sentIntent = naught, deliveryIntent = nothing; ...
-
- Use the SmsManager class to create
smsManager
, which automatically importsandroid.telephony.SmsManager
, and applysendTextMessage()
to send the message:... // Use SmsManager. SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage (destinationAddress, scAddress, smsMessage, sentIntent, deliveryIntent); ...
The full method should now look like the following:
public void smsSendMessage(View view) { EditText editText = (EditText) findViewById(R.id.editText_main); // Gear up the destination phone number to the string in editText. Cord destinationAddress = editText.getText().toString(); // Observe the sms_message view. EditText smsEditText = (EditText) findViewById(R.id.sms_message); // Get the text of the SMS message. String smsMessage = smsEditText.getText().toString(); // Set the service eye address if needed, otherwise aught. String scAddress = aught; // Fix pending intents to broadcast // when bulletin sent and when delivered, or ready to null. PendingIntent sentIntent = null, deliveryIntent = nix; // Use SmsManager. SmsManager smsManager = SmsManager.getDefault(); smsManager.sendTextMessage (destinationAddress, scAddress, smsMessage, sentIntent, deliveryIntent); }
If you lot run the app now, on either a device or an emulator, the app may crash depending on whether the device or emulator has been previously set to permit the app to use SMS. In some versions of Android, this permission is turned on by default. In other versions, this permission is turned off past default.
To prepare the app's permission on a device or emulator case, choose Settings > Apps > SMS Messaging > Permissions, and turn on the SMS permission for the app. Since the user can plough on or off SMS permission at any fourth dimension, you need to add a cheque in your app for this permission, and request it from the user if necessary. Y'all will practice this in the side by side step.
2.3 Bank check for and request permission for SMS
Your app must ever go permission to employ anything that is not part of the app itself. In Step 2.1 you added the following permission to the AndroidManifest.xml file:
<uses-permission android:name="android.permission.SEND_SMS" />
This permission enables a permission setting in the Settings app for your app. The user can let or disallow this permission at any fourth dimension from the Settings app. Yous can add code to asking permission from the user if the user has turned off SMS permission for the app. Follow these steps:
-
At the top of MainActivity, below the grade definition, alter the global constant for the
MY_PERMISSIONS_REQUEST_CALL_PHONE
asking lawmaking to the post-obit:private static concluding int MY_PERMISSIONS_REQUEST_SEND_SMS = 1;
When a event returns in the activity, it will comprise the
MY_PERMISSIONS_REQUEST_SEND_SMS
requestCode
and so that your code can identify it. -
Remove the constant declarations for
mTelephonyManager
andMyPhoneCallListener
. -
Remove the
isTelephonyEnabled()
method, and remove all of the code in theonCreate()
method that starts with themTelephonyManager
assignment, leaving simply the get-go ii lines:@Override protected void onCreate(Parcel savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
-
Refactor/rename the existing
disableCallButton()
method todisableSmsButton()
and edit the method to do the following:-
Display a toast to notify the user that SMS usage is disabled.
-
Find and then set the
smsButton
(the message icon) to be invisible then that the user can't send a message. -
Prepare the Retry button to be visible, so that the user can restart the activity and allow permission.
private void disableSmsButton() { Toast.makeText(this, "SMS usage disabled", Toast.LENGTH_LONG).evidence(); ImageButton smsButton = (ImageButton) findViewById(R.id.message_icon); smsButton.setVisibility(View.INVISIBLE); Push button retryButton = (Button) findViewById(R.id.button_retry); retryButton.setVisibility(View.VISIBLE); }
Extract a cord resource (
sms_disabled
) for the hard-coded string "SMS usage disabled" in the toast argument. -
- Refactor/rename the existing
enableCallButton()
method toenableSmsButton()
to ready the SMS bulletin icon button to be visible:private void enableSmsButton() { ImageButton smsButton = (ImageButton) findViewById(R.id.message_icon); smsButton.setVisibility(View.VISIBLE); }
-
Modify the existing
retryApp()
method in MainActivity to remove the phone call toenableCallButton()
. -
In MainActivity, rename and refactor the
checkForPhonePermission()
method tocheckForSmsPermission()
, and modify the lawmaking to the following:individual void checkForSmsPermission() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) { Log.d(TAG, getString(R.string.permission_not_granted)); // Permission not nonetheless granted. Use requestPermissions(). // MY_PERMISSIONS_REQUEST_SEND_SMS is an // app-defined int abiding. The callback method gets the // result of the request. ActivityCompat.requestPermissions(this, new Cord[]{Manifest.permission.SEND_SMS}, MY_PERMISSIONS_REQUEST_SEND_SMS); } else { // Permission already granted. Enable the SMS push button. enableSmsButton(); } }
Use checkSelfPermission() to determine whether your app has been granted a item permission by the user. If permission has not been granted by the user, employ the requestPermissions() method to brandish a standard dialog for the user to grant permission.
When your app calls requestPermissions(), the organization shows a standard dialog for each permission to the user, as shown in the figure beneath.
-
When the user responds to the request permission dialog, the organisation invokes your app'south onRequestPermissionsResult() method, passing it the user response. Find the
onRequestPermissionsResult()
method you created for the previous version of this app.Your implementation of
onRequestPermissionsResult()
already uses aswitch
statement based on the value ofrequestCode
. Aexample
for checking phone permission is already implemented usingMY_PERMISSIONS_REQUEST_CALL_PHONE
. ReplaceMY_PERMISSIONS_REQUEST_CALL_PHONE
withMY_PERMISSIONS_REQUEST_SEND_SMS
, and replaceCALL_PHONE
withSEND_SMS
. The switch block should at present look like the post-obit:... switch (requestCode) { instance MY_PERMISSIONS_REQUEST_SEND_SMS: { if (permissions[0].equalsIgnoreCase (Manifest.permission.SEND_SMS) && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission was granted. Enable sms push button. enableSmsButton(); } else { // Permission denied. Log.d(TAG, getString(R.cord.failure_permission)); Toast.makeText(this, getString(R.string.failure_permission), Toast.LENGTH_LONG).show(); // Disable the sms push button. disableSmsButton(); } } }
If the user allows the permission request, the message push button is re-enabled with
enableSmsButton()
in case it was fabricated invisible by lack of permission.If the user denies the permission requests, your app should take appropriate action. For example, your app might disable the functionality that depends on a specific permission and prove a dialog explaining why it could non perform information technology. For now, log a debug bulletin, display a toast to testify that permission was not granted, and disable the message button with
disableSmsButton()
. - In the
onCreate()
method of MainActivity, add a telephone call to thecheckForSmsPermission()
method:@Override protected void onCreate(Packet savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); checkForSmsPermission(); }
- Remove the
callNumber()
method and theMyPhoneCallListener
inner grade (including theonCallStateChanged()
method, as y'all are no longer using the Telephony Managing director). - Remove the
onDestroy()
method since you are no longer using a listener. - Since the user might turn off SMS permission while the app is still running, add a check for SMS permission in the
smsSendMessage()
method after setting thesentIntent
only before using theSmsManager
class:... PendingIntent sentIntent = null, deliveryIntent = null; // Check for permission commencement. checkForSmsPermission(); // Utilize SmsManager. ...
two.4 Run the app and test permissions
- Run your app. Enter a phone number (or the emulator port number if using emulators), and enter the bulletin to transport. Tap the messaging icon to send the message.
- After running the app, cull Settings > Apps > SMS Messaging > Permissions and turn off SMS permission for the app.
- Run the app once again. Yous should come across the SMS permission request dialog every bit shown below.
- Click Deny. In the app'southward UI, the message icon button no longer appears, and a Retry push appears, equally shown below.
- Click Retry, and then click Allow for SMS permission.
-
Test the app'southward ability to send a message:
-
Enter a phone number.
-
Enter a message.
-
Tap the messaging icon.
-
End of Part 1 - Proceed with Part 2
Source: https://google-developer-training.github.io/android-developer-phone-sms-course/Lesson%202/2_p_sending_sms_messages.html#:~:text=In%20some%20versions%20of%20Android,SMS%20permission%20for%20the%20app.
0 Response to "How to Read Sms Permission in Android Studio"
Post a Comment