Android:: Calling methods form Broadcasr Receiver class? - android

I have an SMSreceiver class, I am new to android, now my question is that is it possible to call any methods in other class from that class. Basically what I am trying to do is to add each received message to the linked list of strings. Here is my code...
public class SMSReceiver extends BroadcastReceiver {
/**
* #see android.content.BroadcastReceiver#onReceive(android.content.Context, android.content.Intent)
*/
static List<String> recNumList = new LinkedList<String>();
static String message;
static Integer count = 0;
static String phoneNum;
static String newMessage = null;
List<String> recMsgs;
public void onReceive(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]);
}
phoneNum = smsMessage[0].getDisplayOriginatingAddress();
message = smsMessage[0].getMessageBody() + "\n" +
"Time Stamp:" + smsMessage[0].getTimestampMillis();
recMsgs.add(message);
}
}
But the application force closes and does not add anything. Can someone help me please?

Well, firstly, you should not be adding sms to an array in a broadcast receiver, since it will then be recycled within like 100 milliseconds, so if you're wanting to keep track of the list of sms, you need to create a service to run in the background.
Alternatively, you could save the sms to the sharedPreferences using:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences();
// i always use default, though it isn't necessarily convention, I don't think;
SharedPreferences.editor editor = pref.edit();
editor.putString("msg", message);
editor.commit();
//issue with that is, then every time you add a new sms to the shared Preferences
// the previous one will be overridden. Resolving that is not something I will cover here
And the reason why you are getting the nullpointerexception is because your recMsgs is never initialized. do that with the following within the onReceive(), though you should really migrate it to a service if you need to maintain an array:
recMsgs = new ArrayList<String>;
then any calls to recMsgs.add(...) will work properly
I THINK that could have been the issue anyway.

Related

Testing a Android Broadcast Receiver for SMS

I have written a SMSReceiver for Android and all works fine on real devices and when I test the App over Telnet.
But how can I create a unit test for the following onReceive Method in Android Studio?
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle!=null){
Object[] smsExtras = (Object[]) bundle.get("pdus");
String format = (String)bundle.get("format");
String strMessage = "";
for (Object smsExtra : smsExtras) {
SmsMessage smsMessage;
if (Build.VERSION.SDK_INT < 23){
smsMessage = SmsMessage.createFromPdu((byte[]) smsExtra);
}else {
smsMessage = SmsMessage.createFromPdu((byte[]) smsExtra, format);
}
String messageBody = smsMessage.getMessageBody();
String messageSource = smsMessage.getOriginatingAddress();
strMessage += "SMS from " + messageSource + " : " + messageBody;
Log.i(AppConstants.DEBUG_TAG, strMessage);
}
}
}
It depends on what you want to test, but it looks like you want to check that the message body and address is correctly parsed and has the expected contents. In that case you can break out that logic into a separate method and unit test it, by passing in a PDU and checking the return value.
If you want to test onReceive, it should be possible to use Mockito, pass in a MockContext and mock Intent's getExtra to return your own test Bundle object. Still, you'll need to verify something in the end. Perhaps you're planning to store the parsed data somewhere later? If so you can use that as your verification point - either by capturing and checking the argument, or verifying that the data was stored (though that's stretching the boundaries of the unit test quite a bit).

can we create more than one inner broadcast receiver in different activities

Can we create more than one broadcast receiver in different activities.
like every activity has 1 broadcast receiver and also register in manifest.
i tried and work good but my query is that it good or not and it consuming more memory ? or how can i eliminate it, by creating one broadcast receiver which handles all processes. like i want to store different SMS my application has different kinds of status which i receive via SMS . so i created different broadcast receiver at different activities.
I also put some code for receiver
public static class SmsReceiver extends BroadcastReceiver {
String a = "";
DataBaseHandler db;
#Override
public void onReceive(final Context context, final Intent intent) {
db = new DataBaseHandler(context);
if (!intent.getAction().equals(
"android.provider.Telephony.SMS_RECEIVED"))
return;
else if (intent != null) {
Bundle bndl = intent.getExtras();
SmsMessage[] msg = null;
String abc = "";
String msgs = "";
if (null != bndl) { // if start
Object[] pdus = (Object[]) bndl.get("pdus");
msg = new SmsMessage[pdus.length];
for (int i = 0; i < msg.length; i++) {
msg[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
if (msg[i].getOriginatingAddress().equals("15555215556"))
{
abc = msg[i].getOriginatingAddress();
msgs = msg[i].getMessageBody().toString();
}
}
if (abc != "" && ! msgs.equals(""))
{ // inner if start
String[] str_split = msgs.split("\\n|:|,");
String temp = str_split[0].substring(str_split[0].lastIndexOf(' ') + 1).trim();
ArrayList<String> numb =new ArrayList<String>();
if (temp.equals("DEACTIVATED") || temp.equals(" ACTIVATED") )
{
String numbs ;
for (int j = 1; j < 10; j++) {
numbs = str_split[j].substring(str_split[j].lastIndexOf(',') + 1).trim();
numb.add(numbs);
}
for (int i = 1; i < numb.size(); i++)
a += i + " " + numb.get(i) + "\n";
db.update_sys_pwd(temp);
}
else
{
return;
}
}// inner if over
} // if over
}
} // onReceive over
}
Please help me because i never work with telephony ,GSM API .
or how can i create 1 receiver which handles all other receiver for update data. like to register all broadcast receiver inside 1 receiver and then it set to manifest file.
Thanks in advance.
It is better to let single BroadcastReceiver hanle single event (SOLID principle). However, you can register several receivers, each receiving different event.
There is another problem in your code - BroadcastReceiver is running on main thread and Android suppose that code in BroadcastReceiver will finish very fast. You should not do any long running actions (writing to database) in it. Instead, get received data and start IntentService for processing that data by passing received values via Intent

Unable to Get Push Value in android

protected void onMessage(Context context, Intent intent) {
String msg = intent.getStringExtra("payload");
String newspushid1= intent.getStringExtra("payload1");
gc.setnews_pushid(newspushid1);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
BackgroundAlert bg = new BackgroundAlert(mNotificationManager, msg);
bg.onReceive(getApplicationContext(), intent);
}
In this i am Getting value of msg and Push id (helloworld and 101 respectively) i want get this value in another activity .
if (gdata.getPush_message() != null) {
String push_id_value = gdata.getnews_pushid();
Log.e("CATID", "ID-->" + push_id_value);
}
I have apply this code for getting value .from GCMIntentService class but i am getting same value push_id_value ,getPush_message in another activity which is hello world i am unable to get value 101 in another activity please check my code tell me solution .
Create a Constant Class like :
public class Constant {
public static String PAYLOAD = "";
public static String PAYLOAD_1 = "";
}
Now, you can set this value in Activity1 like
Constant.PAYLOAD = intent.getStringExtra("payload");
Constant.PAYLOAD_1= intent.getStringExtra("payload1");
Now, get this value in Activity2 like:
String push_id_value = Constant.PAYLOAD;
String push_id_value1 = Constant.PAYLOAD_1;
And/or for Preference go to my this answer:Android. How to save user name and password after the app is closed?
In your current Activity,
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
Use this technique to pass values from one Activity to another.

Android incoming sms popup

I want to match a String sms phone number (incoming sms) to a String Studentno (variable). How can i match and notify popup msg if successful. here's my code:
public void onReceive( Context context, Intent intent )
{
// Get SMS map from Intent
Bundle extras = intent.getExtras();
String messages = "";
String address = "";
String studentsno = "+0999234678";
String no;
if ( extras != null )
{
// Get received SMS array
Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );
// 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();
address = sms.getOriginatingAddress();
messages += "SMS from " + address + " :\n";
messages += body + "\n";
no = sms.getOriginatingAddress().toString();
// Here you can add any your code to work with incoming SMS
if(no == studentsno){
Toast.makeText( context, "SUCCESS", Toast.LENGTH_LONG ).show();
}
// I added encrypting of all received SMS
putSmsToDatabase( contentResolver, sms );
}
// Display SMS message
Toast.makeText( context, messages, Toast.LENGTH_SHORT ).show();
}
}
This is my problem. how can I match 2 Strings to display popup msg? :
if(no == studentsno){
Toast.makeText( context, "SUCCESS", Toast.LENGTH_LONG ).show();
}
In Java, all strings are objects. When you use the == operator with objects, you are testing whether two objects are the same object.
Because of string interning, strings might be the same object but often not, and you are not able to influence this.
The Java Object class implements an equals method which simply tests if two objects are the same object. Any class which inherits from Object may override this method to provide it's own equality test. string does this by overriding the equals method to test whether two strings (the same object or different objects, it doesn't matter) contain the same content.
Therefore, when testing whether two strings have the same content, you should use string1.equals(string2).
http://en.wikipedia.org/wiki/String_interning
Try
if(no.equals(studentsno))
instead of
if(no == studentsno)
EDIT: Long story short, String.equals() will compare if the values of the given strings are equal (this is what you need in your situation).
== will check if the compare objects are referring to the exact same String object. So even if the comparing Strings have the same value, they are not referring to the same String object.

Is it possible to compare my received msg with resource in xml or textview and edittext

I can start another activity when i receive a sms. what I want to know is how to compare the text message with the content in my resources(xml string) and also the textview, editText. Is it possible to get reference from textview and edittext value in broadcast receiver class? Below is the code starting an activity without comparing any value.
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;
String str = "";
String phonenumber = "";
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]);
phonenumber=msgs[i].getOriginatingAddress();
str += msgs[i].getMessageBody().toString();
str += "\n";
}
//=======launch the ShowMap1 when recieve SMS==============//
Intent mainActivityIntent = new Intent(context, ShowMap2.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainActivityIntent.putExtra("phn", phonenumber);
mainActivityIntent.putExtra("sms", str);
context.startActivity(mainActivityIntent);
//========================END=============================//
}
}
}
as far as I understood that will be a global receiver that will get SMS.
So it means that the device can be on sleep, on the home screen, on the some game, on the gmail, or any other app; so that means that the Activity and the EditText do not exist at the moment that this receiver is being fired.
You can save a previously entered value from the activity on the SharedPreferences for example, and compare from those values.
To compare from an XML resource is very simple, you're receiving a reference to your application context with this receiver, just use it to get the value with this code:
String compare = context.getString(R.string.___);

Categories

Resources