How do I send a text message in Android? - java

How do I send a text message? It seems simple but it doesn't work for me.
I have the permission in the manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.healthapp.healthapp">
<uses-permission android:name="android.permission.SEND_SMS"/>
<application ...
I then have this code in my onClick:
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
But when I run this I get "Unfortunately App has stopped."
And the error message of:
FATAL EXCEPTION: main
Process: com.healthapp.healthapp, PID: 13477
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW typ=vnd.android-dir/mms-sms (has extras) }

You've got two different methods of sending SMS in your code. If you want to use SmsManager, then you don't need the Intent/startActivity() method, which attempts to open another app to handle the SMS.
You can just remove everything after the smsManager.sendTextMessage() line, and you won't get that Exception anymore.
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("07123456789", null, "Hello there!", null, null);

If you want by Intent then
sendSmsByViewIntent()
Intent smsVIntent = new Intent(Intent.ACTION_VIEW);
// prompts only sms-mms clients
smsVIntent.setType("vnd.android-dir/mms-sms");
// extra fields for number and message respectively
smsVIntent.putExtra("address", phoneNumber.getText().toString());
smsVIntent.putExtra("sms_body", smsBody.getText().toString());
try{
startActivity(smsVIntent);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
Send by SmsManager then,
sendSmsByManager()
try {
// Get the default instance of the SmsManager
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber.getText().toString(),
null,
smsBody.getText().toString(),
null,
null);
Toast.makeText(getApplicationContext(), "Your sms has successfully sent!",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(getApplicationContext(),"Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
send by ,
ACTION_SENDTO
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + phoneNumber.getText().toString());
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", smsBody.getText().toString());
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(MainActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
should try any one these methods. but you are trying with two types in same time.
Finally main thing is permission at manifest.xml
<uses-permission android:name="android.permission.SEND_SMS"/>

Related

How to send fixed string value as sms message?

I'm making an application where a fixed value of a string will be sent to a number as sms. I can send sms when the value is not fixed but when I try to send a string that has a fixed value, I cannot receive the sms.
EditText etNumber;
String spamMessage = "Congratulations! Your number just won 2,000,000 PESOS!! REF NO.: PH3413RN For claim, kindly email your name and occupation to:walakongmagawa#gmail.com";
public void MyMessage() {
String phoneNum = etNumber.getText().toString().trim();
if (etNumber.getText().toString().equals("123456789")) {
if (!etNumber.getText().toString().equals("")) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, spamMessage, null, null);
Toast.makeText(this, "Message has been sent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter number or message", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
I expect the output of the value of "spamMessage" will be sent via sms.
I have been working on sending sms recently , hope this will work for you too:
void sendMessage(String phoneNumber){
String messageToSend = "Hey whatsup";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, messageToSend, null, null);
Toast.makeText(context, "Message Sent",
Toast.LENGTH_LONG).show();
} catch (Exception ex) {
Toast.makeText(context,ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
Try this modified code, hope it will work. If it doesn't let me know.
EditText etNumber;
String spamMessage = "Congratulations! Your number just won 2,000,000 PESOS!! REF NO.: PH3413RN For claim, kindly email your name and occupation to:walakongmagawa#gmail.com";
public void MyMessage() {
String phoneNum = etNumber.getText().toString().trim();
if (!etNumber.getText().toString().equals("")) {
if (etNumber.getText().toString().equals("123456789")) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNum, null, spamMessage, null, null);
Toast.makeText(this, "Message has been sent", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Number is incorrect!", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(this, "Please enter number or message", Toast.LENGTH_SHORT).show();
}
}
Free suggestion: It seems like you're almost reaching 160 chars in the message string. If it exceeds 160 chars You will need to use then sendMultipartTextMessage with pending intent. It is the safest way I guess.

What is the code to send SMS if there is no internet connection?

I want to make an app to send some information to the company via email if I have internet connection as a user and I use email intent
String priceMassage = creatOrderSummery(price, hasWippedCream, hasChocolate, name);
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto: ")); // only email apps should handle this
intent.putExtra(Intent.EXTRA_SUBJECT, "Just Java order for " + name);
intent.putExtra(Intent.EXTRA_TEXT, priceMassage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
displayMessage(priceMassage);
but if I don't internet connection I want the information sent to company mobile number via SMS, how can I do it?
You need to check for internet connectivity first if present use email otherwise open the intent to send sms message.
for connectivity check see this helpful answer : https://stackoverflow.com/a/8548926/4428159
For sending sms I'm assuming you need to just open the sms app and send the message so have a look at this code: https://stackoverflow.com/a/9798870/4428159
For this you don't need sms permission in your application.
public void sendSMS(View v)
{
Uri uri = Uri.parse("smsto:12346556");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "Here you can set the SMS text to be sent");
startActivity(it);
}
you need to check if the device is connected to the internet
you can check internet connection via ConnectionManager class.
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
cm.getActiveNetworkInfo().isConnected(); // return true if internet or otherwise flase
if (internet){
// Email send code here
} else {
// SMS send code here
}
this is the sample solution
In order to send sms
In AndroidManifest.xml add permission
<uses-permission android:name="android.permission.SEND_SMS" />
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();
}
}
You have two options to send SMS.
Using SmsManager API
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("phoneNo", null, "sms message", null, null);
Using Built-in SMS application
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", "default content");
sendIntent.setType("vnd.android-dir/mms-sms");
startActivity(sendIntent);
Both need SEND_SMS permission.
<uses-permission android:name="android.permission.SEND_SMS" />
More details can be found here
use this code to check intenet connection..in main
TestInternet testInternet = new TestInternet();
testInternet.execute();
out of main
class TestInternet extends AsyncTask<Void, Void, Boolean>
{
#Override
protected Boolean doInBackground(Void... params) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(4000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return false;
}
#Override
protected void onPostExecute(Boolean result)
{
if (!result)
{
// send sms
else
{
//send mail
}
}
}

sms is not reaching on other device while sending through SMS Manager

I am trying to send sms fom my android mobile to another mobile using SMS Manager. Code is working fine , no error. But when I tested after sending the sms , sms has not reached on other device.I search a lot about this but got no solution. Also I have dual sim..is there any issue with it....?
Following is my code
public void test(View v)
{
askPermission();
try {
String phoneNumber = "1234567890";
String message = "This sms is sent by Meenakshi ";
SmsManager smsManager = SmsManager.getDefault();
//ArrayList<String> parts = smsManager.divideMessage(message);
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
Toast.makeText(birthday_wish.this, "Message Sent",
Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(birthday_wish.this, "Message not Sent",
Toast.LENGTH_LONG).show();
}
}
private void askPermission() {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.SEND_SMS},1);
}
In manifest -
<uses-permission android:name="android.permission.SEND_SMS"></uses-
permission>

How to send Whatsapp message to new number

I' d like to send a whatsapp message by clicking on a button to a number that comes from the Android Activity (that in turn fetches from a server).
The number to which I have to send a new is NOT an existing contact on my phone.
I know how to open Whatsapp app from my app.
The following piece of code deals with opening whatsapp from an Adapter:
Intent sendIntent = new Intent();
sendIntent.setPackage("com.whatsapp");
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(sendIntent);
this code opens Whatsapp but I don't know how to pass it the number to which I have to send the message
Try this
public void onClickWhatsApp(View view) {
PackageManager pm=getPackageManager();
try {
Intent waIntent = new Intent(Intent.ACTION_SEND);
waIntent.setType("text/plain");
String text = "YOUR TEXT HERE";
PackageInfo info=pm.getPackageInfo("com.whatsapp", PackageManager.GET_META_DATA);
//Check if package exists or not. If not then code
//in catch block will be called
waIntent.setPackage("com.whatsapp");
waIntent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(waIntent, "Share with"));
} catch (NameNotFoundException e) {
Toast.makeText(this, "WhatsApp not Installed", Toast.LENGTH_SHORT)
.show();
}
}

Sending SMS via Android Application without moving to Message Box Default Application

I want to ask you:
1-How can I send SMS via my applicatin without moving the user to the Messages box
i just want to allow user to insert the text then he/she clicks on the send button
after that directly the text message should be sent to specific number that i write in the code?
I used this Code as shown below, it works well, but it moved me to the message box :(
any Suggestions ?
MyButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
String str= MyEditText.getText().toString();
// For SMS
Uri smsUri = Uri.parse("I wrote my number here");
Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
intent.putExtra("sms_body", "Besm Allah");
intent.setType("vnd.android-dir/mms-sms"); startActivity(intent);
}
});
====================== After Updating ================================
You are using an Intent object (new Intent(Intent.ACTION_VIEW ... ) which invokes the built-in SMS application to help you send an SMS message. Therefore you are redirected to the message box.
For sending message process to be completed without being directed to the message box you need to use PendingIntent. Take a look at this great SMS tutorial which would quite possibly solve your problem. http://mobiforge.com/developing/story/sms-messaging-android
You have to use the provided intent. That allows the user to choose which app to use to send SMS. This is the way Android is designed. It gives the user choice about how apps can send SMS.
If you want to send SMS without the user using their chosen app, then you will need to use an SMS API from a commercial provider (e.g. esendex), and pay them to send SMS for you.
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message)
{
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, SMS.class), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, pi, null);
}
Take a close look at SmsManager to learn what all of the parameters will do for you.
Also here is the tutorial that this code snippet came from: http://mobiforge.com/developing/story/sms-messaging-android
I found the Perfect Sol. :
// Inside OnCreate()
Send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
HelperWordStr= HelperWords.getText().toString();
// For SMS
if (!b) {
try {
sendSMS("Receiver Number", HelperWordStr);
Toast.makeText(ChattingPage.this, "SMS Sent", Toast.LENGTH_LONG)
.show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(ChattingPage.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}
});
// Outside
public void sendSMS(String number, String msg) throws Exception {
if (!b) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, msg, null, null);
}
b = true;
}

Categories

Resources