I have a simple widget that plays a sound file when pressed. Right now, I have this code in the onRecieve method:
@Override
public void onReceive(Context context, Intent intent)
{
super.onReceive(context, intent);
int id = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
SharedPreferences prefs = context.getSharedPreferences(CreateWidget.PREFS, 0);
Log.d("WORKING",SFXAppWidgetProvider.KEY_SFX_URI_PREFIX+id+" = "+prefs.getString(SFXAppWidgetProvider.KEY_SFX_URI_PREFIX+id, "FAILURE"));
Log.d("WORKING", "Received Intent: " + intent.getAction());
if (intent.getAction().equals(ACTION_PLAY_SOUND))
{
try
{
if(mPlayer != null)
{
mPlayer.stop();
mPlayer.release();
Uri sfxURI= Uri.parse(prefs.getString(SFXAppWidgetProvider.KEY_SFX_URI_PREFIX+id, "null"));
mPlayer.setDataSource(context, sfxURI);
mPlayer.prepare();
mPlayer.start();
Log.d("WORKING","MediaPlayer already existed, released it");
}
else
{
Uri sfxURI= Uri.parse(prefs.getString(SFXAppWidgetProvider.KEY_SFX_URI_PREFIX+id, "null"));
mPlayer = MediaPlayer.create(context, sfxURI);
mPlayer.start();
Log.d("WORKING","MediaPlayer did not exist, making a new one");
}
} catch (IllegalStateException e)
{
e.printStackTrace();
} catch (IllegalArgumentException e)
{
e.printStackTrace();
} catch (SecurityException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
What happens is that the log keeps reporting that it’s creating a new MediaPlayer instance every time I play the sound. I’m guessing that AppWidgetRecievers/BroadcastReceivers aren’t meant to have objects or something? Anyone know an alternate way to play sounds (preferrably lightweight, since it’s only a widget. And I guess it may be more efficient to use a SoundPool since it’s possible to have multiple different sounds)?
Manifest-registered
BrodadcastReceivers, like anAppWidgetProvider, live only as long as theonReceive()call does. It is not safe for them to do anything that lives much past the end ofonReceive(), and they are not reused.If your goal is to play sound for an extended period, have the
AppWidgetProviderdelegate the work to aServicethat manages the audio playback.There may be scenarios in which
SoundPoolis a better option thanMediaPlayer, but it is unlikely that any of those scenarios have anything to do with app widgets.