Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I access MainActivity's objects or methods inside BroadcastReceiver?

I'm creating an android app that uses AlarmManager to create an alarm by playing a sound. To do this, I first create a PendingIntent, for which I have to create a class called AlarmReceiver, which extends BroadcastReceiver. In this new class, I override the onReceive method, in which I also start the sound. What I have right now works. However, as part of a bigger project, I will be later getting some data from a database. Regarding my question, this data is not important; what's important is that, after analyzing all the data, it will all come down to a boolean variable, which will be true or false. This variable will be in MainActivity and I want to access it in my BroadcastReceiver class to check it and if true, I would stop the music. I've checked many SO questions related to these, but I still haven't found a solution.

The code for the MainActivity is:

package com.example.alarmsound;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.content_main);

    Calendar t = Calendar.getInstance();
    t.add(Calendar.SECOND, 5);

    Context context = this;
    AlarmManager alarmMgr;
    alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    alarmMgr.set(AlarmManager.RTC_WAKEUP, t.getTimeInMillis(), pendingIntent);
    boolean result; //the variable I want to access to BroadcastReceiver class
}
}

And the code for the BroadcastReceiver class is:

public class AlarmReceiver extends BroadcastReceiver{
public AlarmReceiver() {}

@Override
public void onReceive(Context context, Intent intent) {
    final MediaPlayer mp = MediaPlayer.create(context, R.raw.music);
    Log.d("Music", "It went here.");
    mp.start();

    //here, I want to access result
}
}

I would really appreciate any help.

like image 207
Dosje Avatar asked Dec 05 '25 09:12

Dosje


1 Answers

In MainActivity:

Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("some_constant", result);

In your broadcast receiver:

boolean result = intent.getBooleanExtra("some_constant", false);
like image 181
Francesc Avatar answered Dec 06 '25 21:12

Francesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!