sabo
sabo

Reputation: 943

When my app is closed Strings are returning null in a class extending BroadcastReceiver when references static methods in another class

I am creating an app that has an sms sending feature. I am currently having an issue that involves the an AlarmManager (which is functioning properly) that calls a class that extends BroadcastReceiver. The class using the AlarmManager is MainMenu.class and the class extending BroadcastReceiver is AlarmReceiver.class.

Inside the MainMenu class the user enters the phone number and the message. In the AlarmReceiver class, I am attempting to send the sms by accessing a getPhoneNumber() method and a getMessage() method. When I do this and the app is closed the phone number and message both return null to the AlarmReceiver class even though it is accessing static methods in the MainMenu class.

Here is the code for the AlarmManager in MainMenu.class:

int hours, minutes;

hours = timePicker.getCurrentHour();
minutes = timePicker.getCurrentMinute();

Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, hours);
cal.set(Calendar.MINUTE, minutes);

Intent intentAlarm = new Intent(MainMenu.this, AlarmReceiver.class);
intentAlarm.putExtra("phoneNumber", phoneNumber);
intentAlarm.putExtra("message", message);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),  PendingIntent.getBroadcast(MainMenu.this, 1, intentAlarm,
                                        PendingIntent.FLAG_CANCEL_CURRENT));

Here is the code for the code for the AlarmReceiver class:

public class AlarmReceiver extends BroadcastReceiver
{

    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Intent intentAlarm = new Intent();
        String phoneNumber = intentAlarm.getStringExtra("phoneNumber");
        String message = intentAlarm.getStringExtra("message");
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber,  null, message, null, null);
    }//end onReceive

}//end AlarmReceiver

I have even gone as far as trying to use SharedPreferences to remember the phone number and message but that still return a null also.

Thanks in advance.

Upvotes: 1

Views: 65

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132992

I have even gone as far as trying to use SharedPreferences to remember the phone number and message but that still return a null also

No need to use SharedPreferences or static way to access variables from MainMenu class.

You can pass required data using Intent from MainMenu to AlarmReceiver:

Intent intentAlarm = new Intent(MainMenu.this, AlarmReceiver.class);
intentAlarm.putExtra("phone_number",MainMenu.getPhoneNumber());

Now get phone number from intent which is second parameter in onReceive method of AlarmReceiver class using phone_number key.

Upvotes: 1

Related Questions