我正在创建一个应用程序,我需要创建一个BroadcastReceiver,因为在播放音乐时我需要做一些事情。
这就是我所拥有的:
(BroadcastReceiver Class)
public class MusicBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive( Context context , Intent arg1 )
{
AudioManager manager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
manager.setMode(AudioManager.MODE_NORMAL);
System.out.println("Playing: " + manager.isMusicActive());
if (manager.isMusicActive())
{
//context.startService(new Intent(context, TimerService.class));
AlarmManager mgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, TimerService.class);
PendingIntent pendIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long timeToWake = System.currentTimeMillis() + ( 30 * 1000);
mgr.set(AlarmManager.RTC_WAKEUP, timeToWake, pendIntent);
System.out.println("Started service");
}
}
}
当音乐开始播放时,接收器会被调用,完美的行为。但是当我调用“manager.isMusicActive()”时,这不会返回正确的值。在我的主要活动中,我创建了一个按钮,按下该按钮将使用相同的代码检查音乐是否处于活动状态。并且“isMusicActive()”完美地运行(这是代码)
btn_CheckMusic.setOnClickListener(new OnClickListener()
{
public void onClick( View v )
{
AudioManager mAudioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
if (mAudioManager.isMusicActive())
{
Intent i = new Intent(SERVICECMD);
i.putExtra(CMDNAME, CMDSTOP);
getActivity().sendBroadcast(i);
Toast.makeText(getActivity(), "Music Stopped", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getActivity(), "Music isn't playing", Toast.LENGTH_SHORT).show();
}
}
});
所以我不知道是什么导致它在Receiver类中搞砸了