Can not send call log as message using SMSmanager Android [duplicate] - java

Am new for android . I want send sms after click send button
first i have used sms manager api.
package com.example.smsproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;`enter code here`
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Page2Activity extends Activity {
Button button;
EditText textPhoneNo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
textPhoneNo = (EditText) findViewById(R.id.mobilenumber);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
//String phoneNo = textPhoneNo.getText().toString();
String phoneNo = "tel:xxxxxxxxxx";
String messageText = "SMS FROM ANDROID";
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, messageText, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent Successfully!",
Toast.LENGTH_LONG).show();
}catch (Exception e){
Toast.makeText(getApplicationContext(),
"SMS failed, please try again later ! ",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
});
}
}
set send_sms permission on android_manifest.xml
i got zero errors but sms not sending. If you have know answer.
please let me know, thanks for reading.

To complete #Android Fanatic answer
If the text is too long, the message does not go away, you have to respect max length depending of encoding.
More information can be found here.
I'd prefer this method
SmsManager sms = SmsManager.getDefault();
ArrayList<String> parts = sms.divideMessage(message);
ArrayList<PendingIntent> sendList = new ArrayList<>();
sendList.add(sentPI);
ArrayList<PendingIntent> deliverList = new ArrayList<>();
deliverList.add(deliveredPI);
sms.sendMultipartTextMessage(phoneNumber, null, parts, sendList, deliverList);

Also SMS Manager doesn't sent messages if the message is longer than 160 for English text, and 70 for 16-bit alphabet text. Try sending small English text to see if it's the case.
(You can sent multiple part messages to send long texts).

String incomming = "9876543210";
android.telephony.SmsManager sms=android.telephony.SmsManager.getDefault();
sms.sendTextMessage(incomming, null,"Here Is Sms", null, null);

Log.d("SMS ready to send", "----FIRST CALL----");
String number = "111111111111"; //ed1.getText().toString();
String message = "Test SMS DATA"; //ed2.getText().toString();
Log.d("SMS ready to send", "----SECOND CALL----"+number);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(number, null, message, null, null);
Log.d("SMS ready to send", "----THIRD CALL----");

Related

Issue with sharing variables between Activities

The code is heavily borrowed from https://github.com/hastarin/android-udpsender and where his code is very versatile, I want a simple way to send a udp packet to an Arduino that will unlock a garage door.
Basically page one (MainActivity) has a big "Open" button and a small "Set Params" button. Page two (Main2Activity) is mostly the borrowed code with lots deleted and provides a way to input the IP address, port and the unlock code word. Currently there is "Send" button that sends the assembled udp packet to the client and it works as intended.
The issue is that I really don't want to have to access the second page regularly. I need the "sendData" routine in MainActivity to have access to the stored values for processing.
At this time, pressing the Send button on the MainActivity page results in:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
at com.kke.android.opener.MainActivity.sendData(MainActivity.java:47)
at com.kke.android.opener.MainActivity.onClick(MainActivity.java:30)
Which I take to mean that the the variable values are not available to the sendData routine on that page.
MainActivity
package com.kke.android.opener;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener{
private View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnsend = (Button) findViewById(R.id.buttonSend);
Button btnset = (Button) findViewById(R.id.buttonSet);
btnsend.setOnClickListener(this);
btnset.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonSend:
sendData(v);
break;
case R.id.buttonSet:
editParams(view);
break;
}
}
public void sendData(View view) {
Context context = getApplicationContext();
/**Load global variable from Main2Activity*/
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
//EditText editText = (EditText) findViewById(R.id.editTextIP);
//String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
//editText = (EditText) findViewById(R.id.editTextPort);
//String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
// editText = (EditText) findViewById(R.id.editTextData);
//String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
/** Called when the user taps the Set Params button */
public void editParams(View view) {
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
}
Main2Activity
package com.kke.android.opener.ui;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.kke.android.opener.R;
public class Main2Activity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Restore preferences
SharedPreferences settings = getPreferences(0);
ToggleButton toggleButton = ((ToggleButton) findViewById(R.id.toggleButton));
boolean checked = settings.getBoolean("toggleChecked", false);
toggleButton.setChecked(checked);
toggleButton.setVisibility(View.GONE);
EditText editText = (EditText) findViewById(R.id.editTextIP);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("host", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextPort);
if (checked) {
editText.setInputType(InputType.TYPE_CLASS_TEXT);
}
editText.setText(settings.getString("port", ""), TextView.BufferType.EDITABLE);
editText = (EditText) findViewById(R.id.editTextData);
editText.setText(settings.getString("dataText", ""), TextView.BufferType.EDITABLE);
/** Set up global variable to pass to MainActivity */
Intent intent = new Intent(Main2Activity.this, MainActivity.class);
intent.putExtra("host", "host");
intent.putExtra("port", "port");
intent.putExtra("dataText", "dataText");
startActivity(intent);
}
#Override
public void onPause() {
super.onPause();
// Get current values
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("host", host);
editor.putString("port", port);
editor.putString("dataText", dataText);
editor.putBoolean("toggleChecked", ((ToggleButton) findViewById(R.id.toggleButton)).isChecked());
// Commit the edits!
editor.commit();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_send:
this.sendData(null);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void sendData(View view) {
Context context = getApplicationContext();
EditText editText = (EditText) findViewById(R.id.editTextIP);
String host = editText.getText().toString();
if (!host.matches("\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b")) {
CharSequence text = "Error: Invalid IP Address";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextPort);
String port = editText.getText().toString();
if (!port.matches("^(6553[0-5]|655[0-2]\\d|65[0-4]\\d\\d|6[0-4]\\d{3}|[1-5]\\d{4}|[1-9]\\d{0,3}|0)$")) {
CharSequence text = "Error: Invalid Port Number";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
editText = (EditText) findViewById(R.id.editTextData);
String dataText = editText.getText().toString();
if (dataText.length() < 1 ) {
CharSequence text = "Error: Text/Hex required to send";
Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
toast.show();
return;
}
String uriString = "udp://" + host + ":" + port + "/";
uriString += Uri.encode(dataText);
Uri uri = Uri.parse(uriString);
Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivity(intent);
}
public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
EditText editTextIp = (EditText) findViewById(R.id.editTextIP);
EditText editTextPort = (EditText) findViewById(R.id.editTextPort);
if (on) {
editTextIp.setInputType(InputType.TYPE_CLASS_TEXT);
editTextPort.setInputType(InputType.TYPE_CLASS_TEXT);
} else {
editTextIp.setInputType(InputType.TYPE_CLASS_PHONE);
editTextPort.setInputType(InputType.TYPE_CLASS_PHONE);
}
}
}
All suggestions will be appreciated.
Please remember I am very new to this.
Both of your Activities have the exact same layouts... That is probably confusing...
Anyways, you called getIntent().getExtras() when there was no extras to get (that activity just started).
Sample of your code
Bundle bundle = getIntent().getExtras();
String host = bundle.getString("host");
String port = bundle.getString("port");
String dataText = bundle.getString("dataText");
You can simply do this
Bundle extras = getIntent().getExtras();
// TODO: declare some variables here
String host, port, text;
if (extras != null) {
// TODO: assign your variables here
String host = extras.getString("host");
String port = extras.getString("port");
String dataText = extras.getString("dataText");
}
However, don't be surprised if you don't get anything because the intent could still be empty
What is happening is that your MainActivity is probably launched from the Android launcher and not from MainActivity2.
Basically when you click send, you inspect the intent that brought you here (to this activity). Since you came from the launcher, this intent does not have the data that you need to execute the function. Remember that you are setting the data for this intent in your MainActivity2 (on your oncreate method, which is kind of a bad practice in this context).
To fix this, go to the manifest and make your MainActivity2 your launcher activity:
<activity android:name="<YOUR_ACTIVITY_TWO_NAME">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
This will make sure that your Activity2 will be called first, this linking to MainActivity and sending an intent with actual data.

Android Studio getApplicationcontext()

I am trying to have messages pop up if the user does not enter their username and password, however my problem is the getApplicationcontext(), it says "cannot resolve method". how do i fix it?-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package com.example.rojean.prelim_project;
import android.support.v7.app.AppCompatActivity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends AppCompatActivity {
Button loginBtn;
EditText txtUsername, txtPassword;
AccountsManagement session;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Object getApplication;
session = new AccountsManagement(getApplicationcontext());
txtUsername = (EditText) findViewById(R.id.nameField);
txtPassword = (EditText) findViewById(R.id.passwordField);
Toast.makeText(getApplicationContext(),
"User Login Status: " + session.isUserLoggedIn(),
Toast.LENGTH_LONG).show();
loginBtn = (Button)findViewById(R.id.loginBtn);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String username = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
//Validation method
if(username.trim().length() > 0 && password.trim().length() > 0){
// For testing puspose username, password is checked with static data
// username = admin
// password = admin
if(username.equals("admin") && password.equals("admin")){
// Creating user login session
// Statically storing name="Android Example"
// and email="androidexample84#gmail.com"
session.createUserLoginSession("Android Example",
"androidexample84#gmail.com");
// Starting MainActivity
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Add new Flag to start new Activity
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}else{
// username / password doesn't match&
Toast.makeText(getApplicationContext(),
"Username/Password is incorrect",
Toast.LENGTH_LONG).show();
}
}else{
// user didn't entered username or password
Toast.makeText(getApplicationContext(),
"Please enter username and password",
Toast.LENGTH_LONG).show();
}
}
});
}
}
Try LoginActivity.this instead of getApplicationContext()
Use this instead of getApplicationContext():
Toast.makeText(this, "User Login Status: " + session.isUserLoggedIn(), Toast.LENGTH_LONG).show;
In this way you get the activity's context.
Do not use getApplicationContext(). The best way to get the Activity context is to use LoginActivity.this, where this refers to the context itself.

make progressdialog while waiting to receive SMS

I am new to Android and Java. The following code is to send and wait for receiving SMS. As the process may takes about 3 minutes, I need to have a progressDialog until SMS is received. Could you send me an applet to do this ?
package com.examples.TOLD;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.telephony.SmsManager;
import android.util.Log;
import android.widget.TextView;
public class Sms extends Activity {
/** Called when the activity is first created. */
static TextView smsReceive;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sms);
Intent i = getIntent();
// Receiving the Data
String reg = i.getStringExtra("reg");
String port = i.getStringExtra("port");
String smsMessage =
"REG=" + reg +
"PORT=" + port;
// Show SMS sent message on screen
TextView smsSend = (TextView) findViewById(R.id.smsSend);
smsSend.setText(smsMessage);
Log.i("smsSend",String.valueOf(smsSend.getText()));
// Send SMS message
SmsManager sm = SmsManager.getDefault();
String number = "5556";
sm.sendTextMessage(number, null, smsMessage, null, null);
// Receive SMS message
smsReceive = (TextView) findViewById(R.id.smsReceive);
}
public static void updateMessageBox(String msg)
{
smsReceive.append(msg);
}
}
Here is another class to receive SMS:
package com.examples.TOLD;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class SmsReceiver extends BroadcastReceiver{
public void onReceive(Context context, Intent intent)
{
Bundle bundle=intent.getExtras();
Object[] messages=(Object[])bundle.get("pdus");
SmsMessage[] sms = new SmsMessage[messages.length];
for(int n=0;n<messages.length;n++){
sms[n]=SmsMessage.createFromPdu((byte[]) messages[n]);
}
for(SmsMessage msg:sms){
String num = msg.getOriginatingAddress();
Log.i("SMS sender",num);
if (num.equals("15555215556")) {
Sms.updateMessageBox("\nFrom: " + msg.getOriginatingAddress() +
"\n" + "Message: " + msg.getMessageBody() + "\n");}
}
}
}
I think you can try to reconsider your approach. You can't expect user will be waiting for up to 3 minutes for the SMS. So you code looks right (except the part of the static method cos I explain you later), but once your message is sent, I'd show a message that your app is waiting for the message, and when the message is received in the SmsReceiver, you can communicate with the Sms activity.
But, you shouldn't use that static method to update the content of the activity for several reasons (UI can't be updated in background or most important when the SmsReceiver is fired SMS activity can even non exist). The right way would be sending an intent from the receiver. You can see a detailed step by step example in the pdf contained in this link in the section Receiving SMS messages.
I Don't think sending and receiving should be in the main thread. You can use AsyncTask to receive the message in background. you can show the dialog before starting the task and
close it after recieving
Lookup http://developer.android.com/reference/android/os/AsyncTask.html for painless background threading.
Simply display your progress dialog in OnPreExecute and dismiss it when the task reaches OnPostExecute.

SMS Logger: how to monitor incoming/outgoing sms activity?

I'am trying to create android (Froyo 2.2) SMS logging app.
Using many tutorials I've made the main part of the app and it works like a charm!
Basically it reads last sms (send or received), gets contact name by a phone number, converts milliseconds unixtime to a date and display result on the screen.
Now I want to remove GUI, modify that code so the app will monitor phone for any incoming/outgoing sms activity and if there will be one it will start mentioned code and save result to a file.
I wish whole app to be completely transparent/stealth for user (working in a background).
I'm suspecting that I have to use somehow the ContentObserver class but I've got some problem with implementation (even with start).
Could You help?
Current code:
import android.app.Activity;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.PhoneLookup;
import android.widget.TextView;
import android.net.Uri;
import android.database.Cursor;
import java.util.Date;
public class SMSLog extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
Uri uriSMS = Uri.parse("content://sms/");
Cursor cur = getContentResolver().query(uriSMS, null, null, null, null);
cur.moveToNext();
String body = cur.getString(cur.getColumnIndex("body"));
String add = cur.getString(cur.getColumnIndex("address"));
String time = cur.getString(cur.getColumnIndex("date"));
String protocol = cur.getString(cur.getColumnIndex("protocol"));
String contactName = "";
Uri personUri = Uri.withAppendedPath( ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(add));
Cursor c = getContentResolver().query(personUri, new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null );
if( c.moveToFirst() ) {
int nameIndex = c.getColumnIndex(PhoneLookup.DISPLAY_NAME);
contactName = c.getString(nameIndex);
}
c.close();
cur.close();
String out = "";
Date d = new Date(Long.valueOf(time));
if (protocol == null)
out = "Sending to: "+ contactName + " <"+add +">\nDate: "+d +"\nBody: "+body+"\n\n";
else
out = "Received from: "+ contactName + " <"+add +">\nDate: "+d +"\nBody: "+body+"\n\n";
tv.setText(out);
setContentView(tv);
}
}

Sending out SMS messages from my Android phone in Java, how can I do them one at a time?

Sending out SMS messages from my Android phone in Java, how can I do them one at a time?
I made this application to send out a number of SMS messages from my phone, but how do I change it to send one at a time?
I am trying to make this send a SMS message and wait for the reply code to get back before sending the next one:
import android.telephony.gsm.SmsManager;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.util.Log;
import android.widget.Button;
import java.io.*;
import android.util.LogPrinter;
import java.io.*;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.widget.TextView;
import android.os.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
import java.io.*;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class JSSMS extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.Button01);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast.makeText(JSSMS.this, "Starting SMS", Toast.LENGTH_LONG)
.show();
String message = "Hello This Is John, Please save my new number";
String number;
try {
BufferedReader buffreader = new BufferedReader(
new FileReader(Environment
.getExternalStorageDirectory().toString()
+ "/numbers.txt"));
int i = 0;
while ((number = buffreader.readLine()) != null) {
Toast.makeText(JSSMS.this, "Sending text to:" + number,
Toast.LENGTH_SHORT).show();
sendSMS(number, message);
}
buffreader.close();
} catch (java.io.FileNotFoundException e) {
Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
.show();
} catch (Exception e) {
Toast.makeText(JSSMS.this, e.toString(), Toast.LENGTH_SHORT)
.show();
}
Toast.makeText(JSSMS.this, "DONE!!", Toast.LENGTH_LONG).show();
}
});
}
// ---Sends an SMS message to another device.---
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));
// ---When the SMS has been delivered---
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode()) {
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), "SMS delivered",
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), "SMS not delivered",
Toast.LENGTH_SHORT).show();
break;
}
}
}, new IntentFilter(DELIVERED));
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);
}
}
Here's a general hint to set you in the right direction. When you have a queue of items you want to process in some asynchronous manner, one approach is use the callback/event handler/call-it-what-you-will to trigger the processing of the next element in the queue.
set up your queue of messages
have a method, e.g. 'sendNextMessage' which pops the top message off the queue and sends it
now, in your onReceive method, you can call your sendNextMessage to trigger sending the next one in the queue
For this approach to work, you need to ensure you are guaranteed to get some kind callback regardless of success or failure.
Look at the sendSms() method in this class.
When you call sendTextMessage(), you can pass a "sent" and a "delivered" intent. Target these intents back to your own application. You can have a callback so to speak when the SMS is sent or delivered.
If you look at the AndroidManifest.xml file in that same project as the references source file, you can see there are two receivers defined that register for "sms_sent" (and "sms_received") intents. If you look at the method I mentioned, you can see that before calling sendTextMessage() it creates two intents with the action "sms_sent" and "sms_delivered". This is how you get notified when an SMS is done sending.
First thing first there are four to five steps
Step 1 open button click or any trigger u start sms sending
Step 2 create Pending Intent to be broadcasted with the intent object and OFCOURSE WITH MULTIPLE PENDING INTENT... for multiple sms sending capability...
Step 3 the registered broadcast receiver will receive the pending intent
Step 4 based on the result and the received INTENT, I REPEAT THE INTENT object u send the next message ... here is a code for it
i trust it's readable enough... stay awesome
public class SMSDoer extends Activity {
String SENT = "SMS_SENT";
String DELIVERED = "SMS_DELIVERED";
PendingIntent sentPI, deliveredPI;
BroadcastReceiver smsSentReceiver, smsDeliveredReceiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override
public void onResume() {
super.onResume();
//---create the BroadcastReceiver when the SMS is sent---
smsSentReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent intent) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “SMS Gone With the wind”,
//db.query update database for recurrisive message calling
//using intent object for specific message
sendSMS(“db.phoneNumber", "db.msg");
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;
}
}
};
//---create the BroadcastReceiver when the SMS is delivered---
smsDeliveredReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context arg0, Intent arg1) {
switch (getResultCode())
{
case Activity.RESULT_OK:
Toast.makeText(getBaseContext(), “SMS delivered”,
Toast.LENGTH_SHORT).show();
break;
case Activity.RESULT_CANCELED:
Toast.makeText(getBaseContext(), “SMS not delivered”,
Toast.LENGTH_SHORT).show();
break;
}
}
};
//---register the two BroadcastReceivers---
registerReceiver(smsDeliveredReceiver, new IntentFilter(DELIVERED));
registerReceiver(smsSentReceiver, new IntentFilter(SENT));
}
#Override
public void onPause() {
super.onPause();
//---unregister the two BroadcastReceivers---
unregisterReceiver(smsSentReceiver);
unregisterReceiver(smsDeliveredReceiver);
}
public void SmsMaker(View v) {
//query database
sendSMS(“db.phoneNumber", "db.msg", db.row);
}
//---sends an SMS message to another device---
private void sendSMS(String phoneNumber, String message, int rowId)
{
//create multiple Pending intent
sentPI = PendingIntent.getBroadcast(this,rowId, new Intent(SENT), 0);
deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumber, "+29170000017", message, sentPI,deliveredPI);
}
}

Categories

Resources