Search code examples
javaandroidbroadcastreceiveralarmmanager

onReceive method of BroadcastReceiver does not get called


I am using 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. However, from what I've tested, the onReceive method is not even called from the MainActivity.

After some research, I found out that I should declare the receiver in the manifest file. Thus, I declare it, but it doesn't recognize the name of the class, AlarmReceiver, it shows it in red. I don't fully understand how to properly declare in the manifest file. I know there are other similar SO questions and I've checked them all, but I am still not able to get it work.

The code for the MainActivity is:

package com.example.alarmsound;
public class MainActivity extends AppCompatActivity {

public class AlarmReceiver extends BroadcastReceiver {

    @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();

        Button stop = (Button) findViewById(R.id.stopAlarm);
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mp.stop();
            }
        });
    }
}

@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);
}
}

And the declaration in Manifest is:

<receiver android:name="com.example.alarmsound.AlarmReceiver">
        <intent-filter>
            <action android:name="com.example.alarmsound.MainActivity" />
        </intent-filter>
</receiver>

I could also be doing something wrong in the MainActivity, even though I think I'm doing everything right there.


Solution

  • Change the first line of the receiver declaration to: <receiver android:name="com.example.alarmsound.MainActivity$AlarmReceiver">. That should let Android detect your class through the manifest.

    The $ symbol is used to reference inner classes in the Android Manifest.