Cant send an SMS - java

I'm trying to send sms in android studio using SmsManager.
I tried a lot of things but it doesn't work.
this is the code i'm using right now:
the problem is that it always go to the "catch"...
public void sendSmsFunction(){
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("972111111111", null, "This is a test", null, null);
Toast.makeText(getActivity(), "SMS Sent!",
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getActivity(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
and this is the CRASH-REPORT:
E/sendSmsFunction: CRASH StackTrace: [android.os.Parcel.readException(Parcel.java:1683), android.os.Parcel.readException(Parcel.java:1636), com.android.internal.telephony.ISms$Stub$Proxy.sendTextForSubscriber(ISms.java:842), android.telephony.SmsManager.sendTextMessageInternal(SmsManager.java:311), android.telephony.SmsManager.sendTextMessage(SmsManager.java:294), com.example.ridewithme.SearchTremp.sendSmsFunction(SearchTremp.java:123), com.example.ridewithme.SearchTremp.searchInDB(SearchTremp.java:97), com.example.ridewithme.SearchTremp$2.onDataChange(SearchTremp.java:109), com.google.android.gms.internal.zzbmz.zza(Unknown Source), com.google.android.gms.internal.zzbnz.zzYj(Unknown Source), com.google.android.gms.internal.zzboc$1.run(Unknown Source), android.os.Handler.handleCallback(Handler.java:754), android.os.Handler.dispatchMessage(Handler.java:95), android.os.Looper.loop(Looper.java:160), android.app.ActivityThread.main(ActivityThread.java:6275), java.lang.reflect.Method.invoke(Native Method), com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:874), com.android.internal.os.ZygoteInit.main(ZygoteInit.java:764)]

If you are missing permission then add like below.
private static final int PERMISSION_REQUEST_CODE = 1;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.SEND_SMS)
== PackageManager.PERMISSION_DENIED) {
Log.d("permission", "permission denied to SEND_SMS - requesting it");
String[] permissions = {Manifest.permission.SEND_SMS};
requestPermissions(permissions, PERMISSION_REQUEST_CODE);
}
}
for below M Version add permission in manifest file.
<uses-permission android:name="android.permission.SEND_SMS"/>
for sending sms use code like below:
private void sendSMS(String phoneNumber, String message)
{
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, null, null);
}

Related

Sending SMS from inner class using SmsManager is not working

UPDATE: if I take sendSms() function outside the inner class it works!
but I need it inside. Can someone help?
I'm trying to send sms in backgroud using SmsManager and nothing happens. when I go to Logcat it says:
E/art: Failed sending reply to debugger: Broken pipe
I've tested it on both emulator and real device
This is a part ofMainActivity.java:
SmsReceiver.bindListener(new SmsListener() {
#Override
public void messageReceived(String messageText, String sender) {
if (msgClassifier.isUrgent(messageText, null, null)) {
sendNotification(messageText);
}
else {
if(sharedPrefs.getAutoReplyState(getApplication())){
Toast.makeText(MainActivity.this, "send sms", Toast.LENGTH_SHORT).show();
sendSms(sender,messageText);
}
}
}
});
public void sendSms(String number, String msg){
android.telephony.SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number,null,msg,null,null);
}
The Toast is being showed and I have also printed sender and messageText and it prints what it should print so this is not the problem.
I have been looking for this error and tried to clean project, rebuild, exit android and nothing worked.
I have included SEND_SMS permission in Manifest
Try This:
public void sendSMS(String phoneNo, String msg) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, msg, null, null);
Toast.makeText(getApplicationContext(), "Message Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}

Android - Send SMS without user's assent [duplicate]

I'm rather new to Android.
Im trying to send SMS from Android application.
When using the SMS Intent the SMS window opens and the user needs to approve the SMS and send it.
Is there a way to automatically send the SMS without the user confirming it?
Thanks,
Lior
You can use this method to send an sms. If the sms is greater than 160 character then sendMultipartTextMessage is used.
private void sendSms(String phonenumber,String message, boolean isBinary)
{
SmsManager manager = SmsManager.getDefault();
PendingIntent piSend = PendingIntent.getBroadcast(this, 0, new Intent(SMS_SENT), 0);
PendingIntent piDelivered = PendingIntent.getBroadcast(this, 0, new Intent(SMS_DELIVERED), 0);
if(isBinary)
{
byte[] data = new byte[message.length()];
for(int index=0; index<message.length() && index < MAX_SMS_MESSAGE_LENGTH; ++index)
{
data[index] = (byte)message.charAt(index);
}
manager.sendDataMessage(phonenumber, null, (short) SMS_PORT, data,piSend, piDelivered);
}
else
{
int length = message.length();
if(length > MAX_SMS_MESSAGE_LENGTH)
{
ArrayList<String> messagelist = manager.divideMessage(message);
manager.sendMultipartTextMessage(phonenumber, null, messagelist, null, null);
}
else
{
manager.sendTextMessage(phonenumber, null, message, piSend, piDelivered);
}
}
}
Update
piSend and piDelivered are Pending Intent They can trigger a broadcast when the method finish sending an SMS
Here is sample code for broadcast receiver
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = null;
switch (getResultCode()) {
case Activity.RESULT_OK:
message = "Message sent!";
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
message = "Error. Message not sent.";
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
message = "Error: No service.";
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
message = "Error: Null PDU.";
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
message = "Error: Radio off.";
break;
}
AppMsg.makeText(SendMessagesWindow.this, message,
AppMsg.STYLE_CONFIRM).setLayoutGravity(Gravity.BOTTOM)
.show();
}
};
and you can register it using below line in your Activity
registerReceiver(receiver, new IntentFilter(SMS_SENT)); // SMS_SENT is a constant
Also don't forget to unregister broadcast in onDestroy
#Override
protected void onDestroy() {
unregisterReceiver(receiver);
super.onDestroy();
}
If your application has in the AndroidManifest.xml the following permission
<uses-permission android:name="android.permission.SEND_SMS"/>
you can send as many SMS as you want with
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(...);
and that is all.
Yes, you can send SMS using the SmsManager. Please keep in mind that your application will need the SEND_SMS permission for this to work.
Yes, you can send sms without making user interaction...But it works, when user wants to send sms only to a single number.
try {
SmsManager.getDefault().sendTextMessage(RecipientNumber, null,
"Hello SMS!", null, null);
} catch (Exception e) {
AlertDialog.Builder alertDialogBuilder = new
AlertDialog.Builder(this);
AlertDialog dialog = alertDialogBuilder.create();
dialog.setMessage(e.getMessage());
dialog.show();
}
Also, add manifest permission....
<uses-permission android:name="android.permission.SEND_SMS"/>

Why Retrofit can't resolve No connection - Check internet connection on Android?

Hello guys I have one specific problem. I'm using retrofit library for all of my network calls. And I have one method to send points to another user and if any error occurs, the server will return me code 400 and string alongside it that I will have to show to user. This thing is working I created it like this ( NetworkSDK is sending a body with params and expect to recieve an error status string if it occurs) so logically I am processing my errors in onResponse method (if Networksdk recieve an object with error string) and if onFailure occurs there is no error. But now I have a bigger problem. If there is no connection at all, if user turns off internet in that fragment it will again go to onFailure and show message that points are sent. Ordinary I would do that via status code if status code is 200 than it's okey but for some reasons I can't get any status code via response.code() command. Here is the code :
#Override
public void onClick(View v) {
try {
final String cardNo;
String amountstring = bodovi.getText().toString();
final Integer amount = Integer.valueOf(amountstring);
cardNo = brojkartice.getText().toString();
Log.d("Broj bodova:", amount.toString());
Log.d("Broj kartice:", cardNo);
final SendPoints Posiljka = new SendPoints();
Posiljka.setAmount(amount);
Posiljka.setCardNumber(cardNo);
NetworkSDK.getInstance().SendPoints(Posiljka, new Callback<SendPointsResponse>() {
#Override
public void onResponse(Call<SendPointsResponse> call, Response<SendPointsResponse> response) {
Log.d("Response code:", "" + response.code());
Log.d("Kartica", Posiljka.getCardNumber());
Log.d("Broj bodova", Posiljka.getAmount().toString());
try {
SendPointsResponse error = (new Gson()).fromJson(response.errorBody().string(), SendPointsResponse.class);
if (error.getCode().equals("-1"))
Toast.makeText(getActivity(), "Neuspješno slanje bodoava. Neispravni ulazni podaci.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-2"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnički podaci nisu popunjeni.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-3"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ima rezervisanu nagradu.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-4"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. U toku jednog mjeseca bodove je moguće poslati maksimalno dva puta.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-5"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Bodove nije moguće poslati samom sebi.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-6"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Korisnik ne može primiti bodove.", Toast.LENGTH_SHORT).show();
if (error.getCode().equals("-100"))
Toast.makeText(getActivity(), "Neuspješno slanje bodova. Greška nepoznata.", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<SendPointsResponse> call, Throwable t) {
Toast.makeText(getActivity(), "Uspješno slanje bodova.", Toast.LENGTH_SHORT).show();
}
});
}catch (Exception e) {
Toast.makeText(getActivity(), "Podaci nisu ispravni, provjerite podatke !", Toast.LENGTH_SHORT).show();
} }
});
}
I basicly need some idea in OnFailure method to detect if user is turned off internet and to display proper message.
You can check this link where is explained in detail if internet connection status is available usgin the ConnectivityManager through the Connectivity Service.
Notice that your app will need permissions for obtaining the network status:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

android programming reuse dialogfragment

My android app has recently been suspended from the play store because of the play store policy:
Do not send SMS, email, or other messages on behalf of the user without providing the user with the ability to confirm content and intended recipient.
My application is mainly a vas sms application for a telecommunication provider. Now am trying to create a confirmation for all sms send using DialogFrament. What I want is to have a single dialog class and method that will be reuse for all sms sending confirmation. I have look through the forum but can find what am looking for.
What is manage to have was
public class sendSMS extends Activity
{
public sendSMS(final String phoneNo, final String sms)
{
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
switch (which)
{
case DialogInterface.BUTTON_POSITIVE:
//Do your Yes progress
try
{
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(),
"Request Sent!",
Toast.LENGTH_LONG).show();
// finish();
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(),
"Request faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
case DialogInterface.BUTTON_NEGATIVE:
//Do your No progress
dialog.cancel();
break;
}
}
};
AlertDialog.Builder ab = new AlertDialog.Builder(this);
ab.setMessage("Are you sure to delete?").setPositiveButton("Yes", dialogClickListener)
.setNegativeButton("No", dialogClickListener).show();
return;
//AlertDialog alertDialog = ab.create();
// alertDialog.show();
}
}
And I am calling it in my activity as:
new sendSMS(phoneNo, sms);
But whenever I click on the function the app crashes with a NullPointerException error. I need help as I have several sms trigger methods rewriting the confirmation over and over just seems a bit over kill.

Sending sms on multiple emulator at time

I'm developing an Android app where i need to send single message to
receive multiple emulator at a time .But the problem is only one
emulator is receiving the message.Here is my code.
public class SMS extends Activity
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnSendSMS = (Button) findViewById(R.id.btn_SendSms);
txtPhoneNo = (EditText) findViewById(R.id.edittext_PhoneNumber);
txtMessage = (EditText) findViewById(R.id.edittext_MessageBody);
btnSendSMS.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
String message = txtMessage.getText().toString();
String phoneNo = txtPhoneNo.getText().toString();
StringTokenizer st=new StringTokenizer(phoneNo,",");
while (st.hasMoreElements())
{
String tempMobileNumber = (String)st.nextElement();
if(tempMobileNumber.length()>0 && message.trim().length()>0)
{
sendSMS(tempMobileNumber, message);
}
else
{
Toast.makeText(getBaseContext(),
"Please enter both phone number and message.",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
private void sendSMS(String phoneNumber, String message)
{
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
//---when the SMS has been sent---
registerReceiver(new BroadcastReceiver()
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS sent",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
Toast.makeText(getBaseContext(), "Generic failure",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NO_SERVICE:
Toast.makeText(getBaseContext(), "No service",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_NULL_PDU:
Toast.makeText(getBaseContext(), "Null PDU",
Toast.LENGTH_SHORT).show();
break;
case SmsManager.RESULT_ERROR_RADIO_OFF:
Toast.makeText(getBaseContext(), "Radio off",
Toast.LENGTH_SHORT).show();
break;
}
}
} , new IntentFilter(SENT));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
}
To send an SMS message to another emulator instance which running on same machine, launch the SMS application. Specify the console port number(ex:5555) of the target emulator instance as as the SMS address.
Please note that this answer is based on :Linuxtopia guide.
You can create the array of emulator id or number then put sendTextMessage into that execute the loop as many element into the the array. OR You can have UI that allow the user to insert the phone number or emulator number in to the list and same procedure as above !!!
note that sendTextMessage `s first argument is "Phone Number" to whom you want to send sms
simply replace it with your requirement every as loop iterate

Categories