我正在尝试在Android中使用Alarm Manager。我想要的是当闹钟响起时它应该播放我为android时钟设置的默认闹钟铃声。我使用了以下代码
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mp = MediaPlayer.create(context, uri);
mp.start();
然而,我得到以下异常
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)
请帮忙
答案 0 :(得分:1)
Hey Guys如果警报音不是,则可能发生崩溃。
答案 1 :(得分:0)
这是因为MediaPlayer.create()
正在返回null
,表明它存在创建问题。这很可能是因为您尝试在BroadcastReceiver
的上下文中创建它,这是一个临时对象,而Context
方法提供的onReceive()
对象是一个简化的功能{{ 1}}。接收器不能阻止或进行任何类型的繁重操作。您应该在应用中运行Context
开始/消息BroadcastReceiver
来进行实际播放。
答案 2 :(得分:0)
我不确定,但是..尝试制作MediaPlayer的实例,然后改用(setDataSource)