Delay for loop cycle in Java - java

I am building an SMS messaging app, with a list of phone numbers in an array which I would like to send to. When I press the SEND button in the app, the message that I type would be sent to all the numbers in that array.
I am using a for loop to run through the numbers and sending the same message to each of them:
for (i=0; i<names.length; i++) {
phoneNo = names[i][3];
sendMessage(phoneNo, message);
}
private void sendMessage(String phoneNo, String message) {
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, message, null, null);
Toast.makeText(getApplicationContext(), "SMS sent", Toast.LENGTH_LONG).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "SMS failed. Please try again!", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
This works perfectly, but now, I want to introduce a one-second delay between sending each message, so I've modified my for loop as follows:
Handler handler1 = new Handler();
for (i=0; i<names.length; i++) {
handler1.postDelayed(new Runnable() {
#Override
public void run() {
phoneNo = names[i][3];
sendMessage(phoneNo, message);
}
}, 1000);
}
This is syntactically correct, but my app crashes whenever I try to send a message now. Can somebody please point out what I've done wrong?
Many thanks:-)

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>

Toast Not Showing In SMS Receive Android App

I'm creating a simple Android application where I'm trying to intercept incoming SMS messages. The problem I am having is that the toast messages from the onReceive isn't showing up. Please help!
Thanks,
Isaiah Thompson
public class SMSR extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
//Print Message
Toast.makeText(context,"Received Message Start",Toast.LENGTH_SHORT).show();
// Get the data (SMS data) bound to intent
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// Retrieve the SMS Messages received
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
// For every SMS message received
for (int i = 0; i < msgs.length; i++) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Sender's phone number
str += "SMS from " + msgs[i].getOriginatingAddress() + " : ";
// Fetch the text message
str += msgs[i].getMessageBody().toString();
// Newline <img draggable="false" class="emoji" alt="🙂" src="https://s.w.org/images/core/emoji/72x72/1f642.png">
str += "\n";
}
}
//Print Message
Toast.makeText(context,"Received Message End",Toast.LENGTH_SHORT).show();
Toast.makeText(context,str,Toast.LENGTH_SHORT).show();
}
}
Try this
new Handler(Looper.getMainLooper()).post(new Runnable()
{
#Override
public void run()
{
Toast.makeText(context, R.string.sent, Toast.LENGTH_SHORT).show();
}
});
Check out this answer
https://stackoverflow.com/a/11436473/6051131
also, make sure your priority (in the manifest file) is less than or equal 2147483647

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