Search code examples
androidbroadcastreceiverandroid-mediaplayer

Why BroadcastReceiver could crash when using MediaPlayer?


I have strange situation in my BroadcastReceiver which uses MediaPlayer. Application crashes after certain number of playing mp3 file.

So, I have Activity

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

This activity launch my service by pressing button

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

Service just creates 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);
    }
}

File /music/beep-7.mp3 is just short beep sound which last less than half second.

My 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>

So, I expect that after pressing Start button I would hear beeping once in three seconds. Beeping will continue even if I close application. In order to stop beeping, I should launch activity and press Stop button.
What I have now is really strange for me:

  • after pressing Start button I hear beeping 7 times and than application crashes
  • after pressing button "Force close" after crash I can hear beeping again 7 times. And then I suppouse service is crashed.

I don't understand LogCat so well. It says:
Unable to start receiver com.ggspot.test.services.MyAlarm: java.lang.NullPointerException
But I don't understand where. And why only after seventh try to play mp3 file.

Updated:

LogCat trace:

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

Updated
Solution is adding CompletionListener to media player and release it after mp3 is played:

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

Solution

  • Reading the LogCat

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

    This says that the NullPointerException occurred on line 58 in MyAlarm.java.

    Problem
    I believe you are trying to use a repeating alarm to replay beep-7.mp3, this is incorrect. When the second alarm calls onReceive() your are trying to re-create your MediaPlayer:

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

    but you never released the first one, only one copy of this MediaPlayer can exist at any time. So the second player is null and player.start() (line 58) throws the NullPointerException:

    Solution
    To repeat beep-7.mp3, simply use MediaPlayer#setLooping():

    player.setLooping(true);
    

    When you are done with the MediaPlayer you must call player.release() before trying to create a second MediaPlayer or you may have the same problem.