我有一个计时器,当计时器结束时我向用户发送通知,我在我的通知中添加了一个“停止”按钮,当用户点击它时,我希望计时器的声音停止。
我尝试将操作注册到我的BroadcastReceiver
TimerActivity
,如下所示:
filter = new IntentFilter();
filter.addAction(TimerService.BROADCAST_ACTION);
registerReceiver(broadcastReceiver, filter);
这是TimerActivity
:
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ScheduledService.STOP_TIMER))
{
if(timerAudio.isPlaying())
{
timerAudio.stop();
timerAudio.release();
timerAudio = null;
}
}
};
这就是我在ScheduledService
类中创建通知的方式:
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
Intent nextIntent = new Intent(STOP_TIMER);
PendingIntent stopTimer = PendingIntent.getBroadcast(this, 0, nextIntent, 0);
Notification noti = new Notification.Builder(this)
.setContentTitle("This is a sample notification")
.setContentText("Subject")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent)
.addAction(R.drawable.ic_launcher, "Stop", stopTimer).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
我在我的清单中注册了Service
和操作,我正确收到了通知,但按钮操作无法正常工作..有人可以解释一下如何解决这个问题吗?
答案 0 :(得分:0)
发布MediaPlayer
控制声音的活动。
如果您没有收到Null Pointer Exceptions,我认为timerAudio
是正确的。
但是,请指定当前视图是否已定义并在上下文中。