如何在不同组件之间传递MediaPlayer对象

时间:2016-06-23 09:23:17

标签: android

我有一个服务(未绑定),它在特定时间发出通知,并开始使用MediaPlayer对象播放音频。我在刷新(或删除)通知时设置了待处理的意图,这启动了广播接收器。现在我希望接收器停止音频,但我无法传递对象,因为我无法使MediaPlayer对象实现可分割。我不想像this问题中所建议的那样绑定服务。有没有办法传递对象?

Calendar current = Calendar.getInstance();
while (!(Integer.parseInt(parts[0]) == current.get(Calendar.HOUR_OF_DAY) &&
Integer.parseInt(parts[1]) == current.get(Calendar.MINUTE) &&

Integer.parseInt(parts[2]) == current.get(Calendar.SECOND))) 
{
current = Calendar.getInstance();
}
mediaPlayer = MediaPlayer.create(AlarmService.this, R.raw.angersextended);

mediaPlayer.start();

Intent intent = new Intent(AlarmService.this, NotifSwipeReceiver.class);

Bundle bundle=new Bundle();
Log.i("abc1", "beforeparcelable");
bundle.putParcelable("mp", (Parcelable) mediaPlayer);
//bundle.putSerializable("mp", (Serializable) mediaPlayer);

Log.i("abc1","afterparcelable");
intent.putExtras(bundle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(AlarmService.this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(AlarmService.this);
mBuilder.setDeleteIntent(pendingIntent);
mBuilder.setContentTitle(time);
mBuilder.setContentText("Alarm" + String.valueOf(j));
mBuilder.setSmallIcon(R.mipmap.ic_launcher);

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
Log.i("abc", String.valueOf(j)+"notif");

这里是广播接收器

public static class NotifSwipeReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MediaPlayer mp= (MediaPlayer) intent.getExtras().getParcelable("mp");
        mp.stop();
        //MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.angersextended);
        //if(mediaPlayer.isPlaying())mediaPlayer.stop();
    }
    public NotifSwipeReceiver(){
    }

}

1 个答案:

答案 0 :(得分:0)

您可以在服务中的运行时注册广播接收器,并在服务停止时取消注册,这样您就不必在组件之间传递MediaPlayer。