Reputation: 323
I am trying to use Alarm Manager in Android. What I want is when the Alarm goes off it should play the default alarm clock tone that I have set for the android clock. I used the following code
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mp = MediaPlayer.create(context, uri);
mp.start();
However, I get following exception
java.lang.RuntimeException: Unable to start receiver com.example.user.alarmmanager.MyBroadcastReceiver: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2732)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference
at com.example.user.alarmmanager.MyBroadcastReceiver.onReceive(MyBroadcastReceiver.java:25)
at android.app.ActivityThread.handleReceiver(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap14(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
Please help
Upvotes: 1
Views: 1047
Reputation: 426
i amn't sure but .. try making an instance of MediaPlayer and then use (setDataSource) instead
Upvotes: 0
Reputation: 15775
It's because MediaPlayer.create()
is returning null
, indicating it had creation problems. This is most likely because you're trying to create it in the context of a BroadcastReceiver
which is a transient object and the Context
object provided to your onReceive()
method is a reduced functionality Context
. Receivers cannot block or do any type of heavy operation. You should have your BroadcastReceiver
start/message a Service
running in your app to do the actual playback.
Upvotes: 0