I'm working in a service which is being shown in foreground where i need to send sms i'm using following code in service class
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, "text", null, null);
and i had took following permission android:name="android.permission.SEND_SMS" but it's not working no message is being sent
Declare:
public static final int PERMISSION_CODE_SEND_SMS = 123;
Check if permission granted :
if (checkSelfPermission(android.Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{android.Manifest.permission.SEND_SMS},
PERMISSION_CODE_SEND_SMS);
return;
}
Now handle the response:
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_CODE_SEND_SMS: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted send SMS now
} else {
// permission denied ask again
}
return;
}
}
}
In main activity checked for permissions
private void checkForSmsPermission() {
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
// Permission already granted. Enable the SMS button.
permission=1;
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
// For the requestCode, check if permission was granted or not.
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (permissions[0].equalsIgnoreCase(Manifest.permission.SEND_SMS)
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted. Enable sms button.
permission = 1;
} else {
// Permission denied.
permission = 0;
// Disable the sms button.
}
}
}
}
and send permission detail to service class via intent as permission variable(int)
checkForSmsPermission();
final Intent intent = new Intent(this, Chat.class);
intent.putExtra("permission",permission);
ContextCompat.startForegroundService(this, intent);
in service class chked permission and sent message(when sent button is hit)
if (permission==1) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
} else
{
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
return;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.