使用MediaPlayer时为什么BroadcastReceiver会崩溃?

时间:2012-10-08 20:26:48

标签: android broadcastreceiver android-mediaplayer

我在使用MediaPlayer的BroadcastReceiver中遇到了奇怪的情况。应用程序在播放一定数量的mp3文件后崩溃。

所以,我有活动

public class MyActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        initButtons();
    }

    private void onStartButtonClicked()
    {
        Intent service = new Intent("com.ggspot.action.LAUNCH_MY_SERVICE");
        startService(service);
    }

    protected void onStopButtonClicked()
    {
        MyAlarm.stop(this);
    }

    private void initButtons()
    {
        Button startButton = (Button) findViewById(R.id.startButton);
        Button stopButton = (Button) findViewById(R.id.stopButton);

        startButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                onStartButtonClicked();
            }
        });

        stopButton.setOnClickListener(new OnClickListener()
        {

            @Override
            public void onClick(View v)
            {
                onStopButtonClicked();
            }
        });
    }
}

此活动通过按下按钮

启动我的服务
public class MyService extends Service
{
    @Override
    public IBinder onBind(Intent intent)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        MyAlarm alarm = new MyAlarm(getApplicationContext(), 3);
        return START_STICKY;
    }    
}

服务只创建BroadcastReceiver

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

    public MyAlarm(Context context, int timeoutInSeconds)
    {
        AlarmManager alarmMgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, MyAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar time = Calendar.getInstance();
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
                timeoutInSeconds * 1000, pendingIntent);
    }

    @Override
    public void onReceive(Context context, Intent intent)
    {
        File file = new File(Environment.getExternalStorageDirectory()
            + "/music/beep-7.mp3");

        Uri uri = Uri.fromFile(file);
        MediaPlayer player = MediaPlayer.create(context, uri);
        player.start();
    }

    public static void stop(Context context)
    {
        AlarmManager alarmMgr = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, MyAlarm.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        alarmMgr.cancel(pendingIntent);
    }
}

文件 /music/beep-7.mp3 只是短暂的哔声,持续时间不到半秒。

我的AndroidManifest:

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity
        android:name=".MyActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".MyService">
        <intent-filter>
            <action android:name="com.ggspot.action.LAUNCH_MY_SERVICE"/>
        </intent-filter>
    </service>

    <receiver
        android:name=".MyAlarm">
    </receiver>
</application>

所以,我希望在按下“开始”按钮后,我会在三秒内听到一声哔哔声。即使我关闭申请,蜂鸣声也会继续。为了停止发出哔哔声,我应该启动活动并按下“停止”按钮。
我现在拥有的对我来说真的很奇怪:

  • 按下开始按钮后,我听到哔哔声7次,而且应用程序崩溃
  • 在按下“强制关闭”按钮后,我可以再次听到7次哔哔声。然后我支持服务崩溃。

我不太了解LogCat。它说:
无法启动接收器com.ggspot.test.services.MyAlarm:java.lang.NullPointerException
但我不明白在哪里。为什么只有在第七次尝试播放mp3文件之后。

更新

LogCat追踪:

10-09 08:42:23.479: E/AndroidRuntime(12578): FATAL EXCEPTION: main
10-09 08:42:23.479: E/AndroidRuntime(12578): java.lang.RuntimeException: Unable to start receiver com.ggspot.test.services.MyAlarm: java.lang.NullPointerException
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:1809)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.app.ActivityThread.access$2400(ActivityThread.java:117)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:985)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.os.Looper.loop(Looper.java:123)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.app.ActivityThread.main(ActivityThread.java:3687)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at java.lang.reflect.Method.invokeNative(Native Method)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at java.lang.reflect.Method.invoke(Method.java:507)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at dalvik.system.NativeStart.main(Native Method)
10-09 08:42:23.479: E/AndroidRuntime(12578): Caused by: java.lang.NullPointerException
10-09 08:42:23.479: E/AndroidRuntime(12578):    at com.ggspot.test.services.MyAlarm.onReceive(MyAlarm.java:58)
10-09 08:42:23.479: E/AndroidRuntime(12578):    at android.app.ActivityThread.handleReceiver(ActivityThread.java:1798)
10-09 08:42:23.479: E/AndroidRuntime(12578):    ... 10 more

更新
解决方案是将CompletionListener添加到媒体播放器并在播放mp3后释放它:

@Override
public void onReceive(Context context, Intent intent)
{
    File file = new File(Environment.getExternalStorageDirectory()
            + "/music/beep-7.mp3");

    Uri uri = Uri.fromFile(file);
    MediaPlayer player = MediaPlayer.create(context, uri);
    player.start();

    player.setOnCompletionListener(new OnCompletionListener()
    {

        @Override
        public void onCompletion(MediaPlayer mp)
        {
            mp.release();                
        }
    });
}

1 个答案:

答案 0 :(得分:1)

阅读LogCat

Caused by: java.lang.NullPointerException
    at com.ggspot.test.services.MyAlarm.onReceive(MyAlarm.java:58)

这表示NullPointerException发生在MyAlarm.java的第58行。

<强>问题
我相信您正在尝试使用重复闹钟重播beep-7.mp3,这是不正确的。当第二个警报呼叫onReceive()时,您正在尝试重新创建MediaPlayer:

MediaPlayer player = MediaPlayer.create(context, uri);

但您从未发布第一个,此MediaPlayer的任何副本都可以随时存在。所以第二个playernullplayer.start()(第58行)会抛出NullPointerException:

<强>解决方案
要重复beep-7.mp3,只需使用MediaPlayer#setLooping()

player.setLooping(true);

完成MediaPlayer后,必须调用player.release()才能尝试创建第二个MediaPlayer,否则您可能遇到同样的问题。