我创建了一个计时器,并实现了一个服务
,该服务在计时器结束时向用户发送通知。
当计时器停止时,我会播放一个音频文件,该文件会继续播放,直到用户通过单击 DialogFragment
上的“确定”来停止它,但是当应用程序处于后台并且我单击通知时,声音会继续播放,因为DialogFragment
没有弹出,我想知道的是:是否可以从服务通知 TimerActivity
,以便当通知打开时我显示 DialogFragment
或者我停止声音?
这是我的服务
代码:
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);
}
}
最佳答案
我会使用Observer pattern为此,因为这基本上就是您正在寻找的。在 Android 上,您可以自己实现它(一屏代码),或者如果您愿意,可以使用现有的实现,例如 EventBus,如 OTTO或GreenRobot's .
关于java - 当服务触发操作时如何通知 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612710/