Android broadcastreceiver creates new instances - android

Well, I have a class extending broadcastreceiver which is listening for messages. Now whenever it receives a message I creates a new instance of my app. So when I am closing it I have to tap back button 2 times.
public class SMSReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
String phoneNumber = "";
if (myBundle != null) {
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += "SMS From: " + messages[i].getOriginatingAddress();
strMessage += " : ";
strMessage += messages[i].getMessageBody();
strMessage += "\n";
phoneNumber = messages[i].getDisplayOriginatingAddress();
}
if (phoneNumber.equals("T-Mobile")) {
Toast.makeText(context, strMessage, Toast.LENGTH_SHORT).show();
abortBroadcast();
}
}
}
}

First of all, I don't really think it is creating a new instance of your app. What is more likely happening is that an activity is being brought to the front. I think you should look at the manifest or post it so we can see how the broadcasts are being directed. It could be that the target of the broadcast also has the effect of starting the activity. So check the manifest, there is nothing in the broadcast receiver that will cause this. Having said that its really up to the Android OS what gets shown when. But as far as two instances. Thats just not happening.
PS. I don't know the exact reason but I would say probably don't issue Toast from a broadcast reeiver, instead communicate to an activity using startActivity().

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

Write received message to SMS provider ( API level 19+ )

I am creating an SMS manager for KitKat and later version. I have implemented all the receivers as directed in the official doc by android.
I have to receive the SMS SMS_DELIVER broadcast receiver and read it and then have to write to the SMS provider.
till now I am able to read the SMS received. I have set my app as the default SMS app in the device. I am also parsing the SMS and can see it in the log.
problem
I am unable to write the SMS to the SMS provider.
here is the broadcast receiver:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i < messages.length; i++) {
String format = bundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
}
}
for (SmsMessage msg : messages) {
Log.i("log", "display msg body : " + msg.getDisplayMessageBody() + "originating address : " + msg.getDisplayOriginatingAddress() + " get message body : " + msg.getMessageBody());
//here I have to write the message to the sms provider.
}
}
}
}
does anyone have any suggestions? please help me.
Update
i have tried android-kitkat-api-19-how-to-write-messages-in-sms-content-provider-without so question but i am unable to get around it. That solution is for writing to the sent SMS without doing anything like sending the SMS. but I want to write the received SMS here.
Thanks to Mike M. for the help. i got help from this answer - sms-doesnt-save-on-kitkat-4-4-already-set-as-default-messaging-app from SO and this post - kitkat-sms-mms-supports .
here is what i have done :
to write the sms into the sms provider of android system i used content provider. and passed value to it. code snippet is :
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, msg.getDisplayOriginatingAddress());
values.put(Telephony.Sms.BODY, msg.getMessageBody());
context.getApplicationContext().getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
this code will save the received sms into the system sms provider and even after your ap is uninstalled other sms app can read it. keep in mind that you need to be the default sms app to do this operation. and you have to provide WRITE_SMS permission in manifest. i have targeted kitkat and versions after it. for previous versions you have to some part of code differently.
the whole SmsReceiver class after completion is :
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
Object[] pdusObj = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdusObj.length];
for (int i = 0; i < messages.length; i++) {
String format = bundle.getString("format");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i], format);
} else {
messages[i] = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
}
}
for (SmsMessage msg : messages) {
Log.i("log", "display msg body : " + msg.getDisplayMessageBody() + "originating address : " + msg.getDisplayOriginatingAddress() + " get message body : " + msg.getMessageBody());
ContentValues values = new ContentValues();
values.put(Telephony.Sms.ADDRESS, msg.getDisplayOriginatingAddress());
values.put(Telephony.Sms.BODY, msg.getMessageBody());
context.getApplicationContext().getContentResolver().insert(Telephony.Sms.Sent.CONTENT_URI, values);
}
}
}
}
I had the same problem. You have to register a SMSBroadcaseReceiver, MMSBroadcastReceiver, a QuickreplyService in order to be be able to be set as default SMS receiver.
This helped me:
https://www.androidauthority.com/how-to-create-an-sms-app-part-2-724264/

android hide special SMSs notification from user and remove it from inbox

My application uses some web services for performing actions in server and getting results from it. Now I want my app to work in offline mode. I have a sms panel that can handle sending and receiving messages to clients. So the thing I need is to listen to messages in client and respond to it if it has a special format. I know how to listen to incoming sms from code, here it is:
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// ---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
Log.d("checking", "sms received!");
String str = "";
if (bundle != null) {
// ---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
String sender = null;
String body = null;
for (int i = 0; i < msgs.length; i++) {
msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
sender = msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
body = msgs[i].getMessageBody().toString();
str += "\n";
}
// ---display the new SMS message---
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
}
}
}
and it works properly. The thing here is I don't want my special messages appear in user inbox or even hide sms notification from him. Is this possible? Should I listen to all incoming messages?
update:
I assume that things are different in KitKat so any solution works in api 19 appreciated.
thanks in advanced.
Try abortBroadcast(); in your BroadcastReceiver
if (intent.getAction().equals(android.provider.Telephony.SMS_RECEIVED)) {
abortBroadcast();
}
i don't know if this works on KitKat or not.

cancelling the broadcast of a receiving SMS doesn't work in the device

I have a Broadcast Receiver in my application in which it invokes the abortBroadcast() method. So it cancels the broadcast of a receiving SMS and checks whether a specific content is available. If it is available application perform some tasks, otherwise clearAbortBroadcast() method is invoked to continue the broadcast of the SMS to the inbox. Also I have set a higher value as the priority in the manifest file.
I am using android 2.2 version for developing the application. Everything is working fine with the emulator and it provides the expected results for me. But when I test the application in the phone which has 4.0.4 version (ICS), it doesn't work. Message broadcast cancellation is not happening and every receiving SMS which contains the specific content reaches the inbox as a normal SMS does.
P.S : Everything works fine with the emulator. I have set the priority as high as "999999". All the permissions have been included.
Here is the code snippet.
public class SMSReciever extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
this.abortBroadcast();
final String pinNumber = "abcd";
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String smsMsg = "";
String replyPhoneNum = "";
if(bundle != null)
{
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]);
smsMsg += "SMS From " + msgs[i].getOriginatingAddress();
smsMsg += "\n";
smsMsg += msgs[i].getMessageBody().toString();
smsMsg += "\n";
replyPhoneNum = msgs[i].getOriginatingAddress();
}
}
if(smsMsg.contains("SecretCode: "+pin+"\n"))
{
String[] splitMsg = smsMsg.split("\\n");
String[] splitFeatures;
Bundle b = new Bundle();
splitMsg = smsMsg.split("\\n");
for(int i=0; i<splitMsg.length; i++)
{
if(!(splitMsg[i].equalsIgnoreCase("null")))
{
splitFeatures = splitMsg[i].split(":");
if(splitFeatures[0].equals("Contact Number"))
{
String contactName = splitFeatures[1];
b.putString("contactname", contactName);
}
}
if(splitMsg[i].contains("email"))
{
String email = "email";
b.putString("email", email);
}
}
b.putString("replyPhoneNum", replyPhoneNum);
Intent i = new Intent(context, NextActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtras(b);
context.startActivity(i);
}
else
{
this.clearAbortBroadcast();
}
}
}
In the android manifest file,
<receiver android:name="SmsReceiver">
<intent-filter android:priority="999999">
<action android:name="android.provider.Telephony.SMS_RECEIVED"></action>
</intent-filter>
</receiver>
That's it. All other permissions have been used correctly. This works fine in the emulator. But not working in the device.

broadcast receiver and music

I've created a simple BroadcastReceiver which react on SMS received.
One message should be able to start an alarm and another one to stop it. The alarm is triggered with a mediaPlayer and works well. But I can't stop it. I know that a new instance of mediaplayer is created each time the right SMS is received but even with a singleton, I can't make it work...
Here is a code snippet :
Bundle myBundle = intent.getExtras();
SmsMessage [] messages = null;
String strMessage = "";
if (myBundle != null)
{
Object [] pdus = (Object[]) myBundle.get("pdus");
messages = new SmsMessage[pdus.length];
for (int i = 0; i < messages.length; i++)
{
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
strMessage += messages[i].getMessageBody();
}
if (strMessage.equals("ATELIO&SON")){
if(onoff == 1){
Toast.makeText(context, "Démarrage localisation sonore", Toast.LENGTH_LONG).show();
playSound();
}
}
else if(strMessage.equals("ATELIO&SON&FIN")){
Toast.makeText(context, "Fin localisation sonore", Toast.LENGTH_LONG).show();
stopSound();
}
}
playsound() and stopsound() are two really simple method, the first one starting the sound and the second one checking if mediaplayer is null and acting accordingly.

Categories

Resources