Start intent from BroadcastReceiver class - android

My application receives SMS and changes to activity to display an alert dialog box in my app. Toast is working well, but it will not change the activity. onReceive() takes SMS that contain email and depending upon that email id my app searches the associated contact number and sends it back in a reply message.
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle extras = intent.getExtras();
String messages = "";
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( "pdus" );
// Get ContentResolver object for pushing encrypted SMS to incoming folder
//ContentResolver contentResolver = context.getContentResolver();
for ( int i = 0; i < smsExtra.length; ++i )
{
SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);
String body = sms.getMessageBody().toString();
String address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
// Here you can add any your code to work with incoming SMS
// I added encrypting of all received SMS
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
Intent i=new Intent(context,AlertActivity.class);
// context.startActivity(i);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}

you are adding addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) after starting AlertActivity Activity. use this way :
Intent i=new Intent(context,AlertActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);

Related

Can't launch the activity again if it's already open

I'am working on SMS manager like app. Now when an SMS is received a new Dialog Activity like a pop-up which shows the user the Sender's number and message. It's OK but if another SMS comes before the user press Back button (the Pop-Up activity still there on the Top), then the new SMS can't be shown to the user.
Every new SMS should show up on the pop-up activity diminish any older SMS if on foreground.
I tried in and out the onReceive method of the Broadcast Receiver class. By digging deeper I found that if the pop-up with an SMS is on foreground, the Pop-up Activity cannot gets called. It just don't come to the OnCreate method.
BroadcastReceiver class:
public class SmsBroadcastReceiver extends BroadcastReceiver {
public static final String SMS_BUNDLE = "pdus";
public static String latestSMSnumber, latestSMScontent;
SmsMessage[] msgs = null;
String str = "";
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i = 0; i < msgs.length; ++i) {
// Convert Object array
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
// Fetch the text message
str += msgs[i].getMessageBody().toString();
str += "\n";
latestSMSnumber = msgs[i].getOriginatingAddress();
latestSMScontent = str;
}
// Display the entire SMS Message
Log.e("TAG1 number: ", latestSMSnumber);
Log.e("TAG2 content: ", str);
latestSMScontent = str;
// Toast.makeText(context, smsMessageStr, Toast.LENGTH_SHORT).show();
Intent i=new Intent(context.getApplicationContext(),NewSMS.class);
// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("Number", latestSMSnumber);
i.putExtra("MsgBody", latestSMScontent);
context.startActivity(i);
}
}
}
I like to show any new SMS with number and msg text in the pop-up window.
Write This in you manifest.xml file in activity tag NewSMS Activity
android:launchMode=”singleTop”
For more information Please read the bellow link
https://android.jlelse.eu/android-activity-launch-mode-e0df1aa72242

How to send hidden SMS on android 6.0+ [duplicate]

I have an auto reply sms Android application I built and I don't want the auto reply (sent sms) to show in the default messaging app. I have searched and searched and couldn't find an answer. Is there a way to bypass writing the sent sms into the default messaging app?
Here my BroadcastReciever I am using to get the data and send out the message
public class SmsReceiver extends BroadcastReceiver {
ParseUser user = ParseUser.getCurrentUser();
// Auto reply message composed of the current reply and url from that business
String msg = user.getString("myCurrentReply") + " " + user.getString("couponUrlChosen");
List smsFromList = user.getList("smsFrom");
String userName = (String) user.get("username");
#Override
public void onReceive(final Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
final String pno = smsMessage[0].getOriginatingAddress();
user.put("lastSmsFrom", pno);
user.saveInBackground();
// show first message
Toast toast = Toast.makeText(context, "Received SMS: " + smsMessage[0].getMessageBody(), Toast.LENGTH_LONG);
toast.show();
// Check Phone Number from SMS Received against Array in User Row
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
Log.d("Username: ", userName);
query.whereEqualTo("username", userName);
query.whereContainedIn("lastSmsFrom", smsFromList);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> smsList, ParseException e) {
if (e == null) {
Log.d("Errors", "none");
if (smsList.size() == 0) {
// Send SMS
sendSms(pno, msg);
// Add Phone number to smsFrom in currentUsers Row
user.addUnique("smsFrom", pno);
// Save Phone Number in Array
user.saveInBackground();
Log.d("List size: ", " " + smsList.size());
}
} else {
Log.d("Error Message: ",
e.getMessage());
}
Log.d("Already sent to this number today. ", " " + smsList.size());
}
});
}
private void sendSms(String phonenumber, String message) {
SmsManager manager = SmsManager.getDefault();
manager.sendTextMessage(phonenumber, null, message, null, null);
}
}
Prior to KitKat, SMS sent using SmsManager require the app sending the message to insert it into the Provider, so it would just be a matter of omitting that.
Starting with KitKat, any app that is not the default SMS app and uses SmsManager to send messages will have the messages automatically written to the Provider for it by the system. There's no way to prevent this, and, furthermore, the app won't be able to delete those messages, either, as it won't have write access to the Provider.*
The app that is the default SMS app is responsible for writing its outgoing messages, so it would be able to omit that step. The system does no automatic writes for the default SMS app.
* There is a security hole in 4.4 only, by which a non-default app can gain write access to the Provider. It is detailed in my answer here, but it will not work in versions after KitKat.

How to open incoming sms from notification directly to my application's intent as textview or listview?

I want to open incoming sms from notification directly to my application's intent , Please help I tried following code to read sms from inbox
public class SmsReceiver extends BroadcastReceiver
{
public static String BODY = "Test";
public static String ADDRESS = "5556";
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
ADDRESS=msgs[i].getOriginatingAddress();
BODY=str;
}
//---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
When a new SMS is received by your device, the android creates a intent and broadcasts the SMS_RECEIVED_ACTION. What you are going to do is create an Intent Filter for the activity of your application that handles the SMS that the phone receives.
When the phone gets a new SMS message and the user clicks on the notification, she is presented with a dialog of apps that can handle this action*****. Your app should be there, and when she decides that she wants your app to handle the incoming message then you can use the getMessagesFromIntent method in order to extract the message (you use that method inside your app).
PS: You cannot set your app as the default message app, which you probably need to do. The user has to explicitly choose your app to open the message, and if she wants it to be the default messaging app (by ticking the set as default checkbox).
Note: It looks like you have to create a broadcast receiver that receives the SMS_RECEIVED_ACTION which you can use prior to API 19 as a constant at android.provider.Telephony.SMS_RECEIVED and launch your own notifications in which you direct the user directly to the application of yours. Unfortunately it seems that the default messaging app will still issue notifications.
Credit: #Mike M.

Android - sendTextMessage Message not showingup in SMS Apps

I am writing an app which will send an SMS automatically to a given number on some conditions, SMS code is working and SMS is also delivered.. but the sent SMS are not showing up in any of the other SMS Clients/Apps installed...
String phoneNumber = "1234512345";
String message = "Test Message";
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, message, null, null);
What am i missing?
I want the sent SMS (sent by my app) to show up in other SMS apps which are installed..
Yes you have sent SMS progrmatically but you haven't informed SMS Content Provider so it will not get your message unless you inform it.
ContentValues values = new ContentValues();
values.put("address", "1234512345");
values.put("body", "Test Message");
getContentResolver().insert(Uri.parse("content://sms/sent"), values);
Make sure to include below permissions in AndroidManifest.xml file:
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
use broadcast receiver in receiving side application
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle bundle = intent.getExtras();
String str="";
String from="";
if (bundle != null) {
Object[] pdus = (Object[])bundle.get("pdus");
final SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += messages[i].getMessageBody().toString();
from = messages[i].getOriginatingAddress().toString();
}
if(from.equals("123456789")){
str= str.trim();
abortBroadcast();
Intent intt = new Intent(context,MainActivity.class);
intt.putExtras("message",str);
intt.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intt);
}
}
in your mainActivity write some code to display the obtained message. the message will be in the intent. so get the String from it.
here the broadcast receiver, receives messages from only number "123456789". the messages from this number will not go to inbox of ur mobile. if u want to see in inbox also remove the method abortBroadcast().

How to avoid SMS's from selected phone numbers being made visible to user? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can we delete an SMS in Android before it reaches the inbox?
I've already gotten receive SMS code running successfully. What I cannot determine is a way (or if it's possible) to process messages sent from specific phone numbers within my app without them being made visible to the user. All other SMS's sent from other phone number would be handled by the normal Android SMS processing. I.e., SMS's from selected numbers should not be visible to the phone user and the rest should. Any suggestions?
Here's the SMSReceiver code (taken straight from Wei-Meng Lee's book):
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//get the received SMS message
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null) {
// retrieve the SMS message
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += "\nMessage Text:\n";
str += msgs[i].getMessageBody().toString();
str += "\nLength="+msgs[i].getMessageBody().toString().length()+"\n";
} // [END FOR]
// display the new SMS message
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
// send a broadcast intent to update the SMS received in the activity
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
} // [END IF]
} // [END onReceive]
} // [END SMSReceiver]
well if you put an if before you start concatenating str, you can check the originating address, and compare it to your blacklist of addresses, if its on the list, then simply use the continue to skip the concatenations

Categories

Resources