我创建了一个计时器,并且我实现了一个Service
,它在计时器结束时向用户发送通知。
当计时器停止时,我播放一个音频文件,该文件一直持续到用户通过单击&#34停止它; OK"在DialogFragment
上,但当应用程序处于后台时,我点击通知声音继续,因为DialogFragment
没有弹出,我想知道的是:是否可以从服务中通知TimerActivity
,以便在通知打开时显示DialogFragment
或停止声音?
这是我的Service
代码:
public class ScheduledService extends IntentService {
public ScheduledService() {
super("My service");
}
@Override
protected void onHandleIntent(Intent intent) {
//Do something, fire a notification or whatever you want to do here
Log.d("debug", "Ring Rind !");
// Build notification
// Actions are just fake
Intent notificationIntent = new Intent(getBaseContext(), CookingTimer.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, notificationIntent, 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, "Call", pIntent)
.addAction(R.drawable.ic_launcher, "More", pIntent)
.addAction(R.drawable.ic_launcher, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
}
}
答案 0 :(得分:1)
我会使用Observer pattern,因为这基本上就是你要找的东西。在Android上,您可以自己实现(1个代码屏幕),或者如果您希望使用像OTTO或GreenRobot's这样的EventBus,则可以使用现有的实现。