Android Smsmanager not sending message more than once - android

I want to send message everytime I click button but with this code I am able to send message only first time.I can only send message again when I clear App data and cache.
public class MainActivity extends AppCompatActivity {
TextView tapme;
private static final int MY_PERMISSIONS_REQUEST_SEND_SMS = 0;
String phoneNo;
String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tapme = (TextView) findViewById(R.id.tapme);
tapme.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendSMS();
}
});
}
protected void sendSMS() {
phoneNo = "+911333444400";
message = "hi";
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
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;
}
}
}
}
Where i do wrong? Any help is greatly appreciated.

protected void sendSMS() {
phoneNo = "1";
message = "hi";
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
} else {
SendTextMsg();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
SendTextMsg();
} else {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again.", Toast.LENGTH_LONG).show();
}
}
}
}
private void SendTextMsg() {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent.",
Toast.LENGTH_LONG).show();
}

Related

Send SMS from a service class on android

I am trying to send SMS from a service class and found the following code which sends SMS from Activity class. Getting an error on "this" in sendSMSMessage method which is quite understandable because the code for sending SMS from Activity class. How I can convert it to sending SMS from Service class? The Service class was written before, working without any issue in production. Trying to add this SMS sending code as an extra functionality.
protected void sendSMSMessage() {
phoneNo = txtphoneNo.getText().toString();
message = txtMessage.getText().toString();
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.SEND_SMS)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.SEND_SMS)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.SEND_SMS},
MY_PERMISSIONS_REQUEST_SEND_SMS);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_SEND_SMS: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
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;
}
}
}
}
Replace this with getActivity() and Voila!

How do I make my application run on background?

My application is all about an EMERGENCY SMS where I just click my volume button and a simulated Message is sent to a certain Phone Number.
I wanted to know how I can make my application run on background when I want and close it whenever I want?
Hoping for your kind help, my Code is this:
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
You have to start a service in your Application class to run it always. If you do that, your service will be always running.Even though user terminates your app from task manager or force stop your app, it will start running again in Background.
You can get more info about service from this link:
https://developer.android.com/training/run-background-service/create-service

Permission send sms android

I am writing an app that will send a message to an inputted number through SMS. However when I try to send the message I get the error that "User 10074 does not have android.permission.SEND_SMS" even though I have this permission in my Manifest.
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("5554", null, "hello", null, null);
// smsManager.sendTextMessage(number,null,matn,null,null);
Toast.makeText(Sms.this, "OK", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Sms.this, "Error"+e, Toast.LENGTH_LONG).show();
}
}
});
and code in manifest
<uses-permission android:name="android.permission.SEND_SMS" />
Please try below code with runtime permission.
call checkAndroidVersion("5554"); from your click listener
public void checkAndroidVersion(String mobile){
this.mobile= mobile;
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(RegistrationActivity.this,Manifest.permission.SEND_SMS);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(RegistrationActivity.this,new String[]{Manifest.permission.SEND_SMS},SEND_SMS);
return;
}else{
sendSms(mobile);
}
} else {
sendSms(mobile);
}
}
private void sendSms(String mobileNo){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(mobileNo, null, "hello", null, null);
// smsManager.sendTextMessage(number,null,matn,null,null);
Toast.makeText(Sms.this, "OK", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(Sms.this, "Error"+e, Toast.LENGTH_LONG).show();
}
}
Also Override onRequestPermissionsResult method
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
sendSms(mobile);
} else {
Toast.makeText(Sms.this, "SEND_SMS Denied", Toast.LENGTH_SHORT).show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app.
try this to ask run time permission
requestSmsPermission();
private void requestSmsPermission() {
String permission = Manifest.permission.READ_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AccountClass.this,"permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AccountClass.this,"permission not granted", Toast.LENGTH_SHORT).show();
}
}
}

How to receive sms in android API 25 (Nougat)

I have been using these code to receive sms in actual device android 4.2 and it was working fine, Now I came to know about new permission module so this code in android 7 nougat not working for me.
public class sms extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
if (bundle != null) {
Object[] smsExtra = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[smsExtra.length];
for (int i = 0; i < msgs.length; i++) {
SmsMessage sms = SmsMessage.createFromPdu((byte[]) smsExtra[i]);
String body = sms.getMessageBody().toString();
String sender = sms.getOriginatingAddress().toString();
Toast.makeText(context, "From :"+sender+"\n"+"body:"+body, Toast.LENGTH_LONG).show();
}
}
}
}
I found this about marshmallow that there is run time permission required, But i don't get it how and where to add it in my code so that it work in Nougat and below apis.
// in manifest.xml
<uses-permission android:name="android.permission.RECEIVE_SMS" />
try this to read sms permisson runtime
requestSmsPermission();
private void requestSmsPermission() {
String permission = Manifest.permission.READ_SMS;
int grant = ContextCompat.checkSelfPermission(this, permission);
if (grant != PackageManager.PERMISSION_GRANTED) {
String[] permission_list = new String[1];
permission_list[0] = permission;
ActivityCompat.requestPermissions(this, permission_list, 1);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(AccountClass.this,"permission granted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(AccountClass.this,"permission not granted", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messagebox);
if (!CheckPermission(MessageBox.this, Manifest.permission.READ_SMS)) {
RequestPermission(MessageBox.this, Manifest.permission.READ_SMS, REQUEST_RUNTIME_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead
//createApplicationFolder();
} else {
// you do not have permission show toast.
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity, Permission) != PackageManager.PERMISSION_GRANTED)
{
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity, Permission))
{ }
else
{
ActivityCompat.requestPermissions(thisActivity, new String[]{Permission}, Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context, Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}

android permission READ_SMS granted but not working (even using REQUEST_CODE_ASK_PERMISSIONS)

I want to create an app that reads all inbox sms and when i tap on a message from the list it sends the data to another activity which contains another list to forward the message to.
the reading SMS worked perfectly before i started working on the other activity.
once i finished the whole app , i ran the application on phone but when there are messages it gives me that android app unfortunately stopped but when i delete all threads it start the app normally with no messages in it. what might be the error ??
here is my main activity and i added the read sms permission in Manifest
public class main extends ListActivity {
final private int REQUEST_CODE_ASK_PERMISSIONS = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_SMS") == PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(main.this, new String[]{"android.permission.READ_SMS"}, REQUEST_CODE_ASK_PERMISSIONS);
return;
}
readAllSMS();
} else {
readAllSMS();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readAllSMS();
} else {
Toast.makeText(main.this, "READING SMS Denied", Toast.LENGTH_SHORT)
.show();
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
protected void readAllSMS() {
Toast.makeText(main.this, "READING SMS Granted", Toast.LENGTH_SHORT)
.show();
List<SMSData> smsList = new ArrayList<>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uri, null, null, null, null);
startManagingCursor(c);
if (c.moveToFirst()) {
for (int i = 0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
smsList.add(sms);
c.moveToNext();
}
}
c.close();
setListAdapter(new ListAdapter(this, smsList));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
SMSData sms = (SMSData) getListAdapter().getItem(position);
String msg = "number : " + sms.getNumber() + "\nsent : " + sms.getBody();
sendSMS(msg);
Toast.makeText(getApplicationContext(), sms.getBody(), Toast.LENGTH_LONG).show();
}
private void sendSMS(String message) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("SMS_Message",message);
startActivity(i);
}
}

Categories

Resources