Reputation: 11
I need to pass a string value from my main activity to a Java class that implements a BroadcastReceiver. Basically I want to get a String value from an EditText in AddNewPrescriptionsActivity.java and pass it to AlarmReceiver.java. It seems that I can't use an Intent or a Bundle to pass it so is there another way to do this?? I have some of my code below..
Here is some of my MainActivity called AddNewPrescriptionsActivity.java:
public void onClick(View v) {
if (v == btnSave) {
calSet.getTime();
if (calSet.compareTo(calNow) <= 0) {
//Today Set time passed, count to tomorrow
calSet.add(Calendar.DATE, 1);
}
setAlarm(calSet);
Toast.makeText(AddNewPrescriptionsActivity.this, "Notification Created", Toast.LENGTH_LONG).show();
}
}
private void setAlarm(Calendar targetCal) {
Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(), pendingIntent);
}
Here is my AlarmReceiver.class which implements BroadcastReceiver
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(arg0, notification);
r.play();
Toast.makeText(arg0, "Received" , Toast.LENGTH_LONG).show();
}}
Thanks in advance!
Upvotes: 0
Views: 112
Reputation: 6114
If I understood your question well, you need to send a String value from your Activity to your Broadcast Receiver. To do this, in your Activity:
Intent in = new Intent("my.action.string");
in.putExtra("state", "activated");
sendBroadcast(in);
And inside the BroadcastReceiver :
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.i("Receiver", "Broadcast received: " + action);
if(action.equals("my.action.string")){
String state = intent.getExtras().getString("state");
//do your stuff
}
}
And inside the manifest.xml:
<receiver android:name=".YourBroadcastReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
<action android:name="my.action.string" />
<!-- and some more actions if you want -->
</intent-filter>
Hope it helps!
Upvotes: 1