java - 当服务触发操作时如何通知 Activity

标签 java android

我创建了一个计时器,并实现了一个服务,该服务在计时器结束时向用户发送通知。 当计时器停止时,我会播放一个音频文件,该文件会继续播放,直到用户通过单击 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,如 OTTOGreenRobot's .

关于java - 当服务触发操作时如何通知 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31612710/

相关文章:

android - 将 byteArray 转换为 android 中的位图?

android - Firebase 无法将类型为 java.lang.String 的对象转换为类型

java - 为什么使用 Socket.setSoTimeout() 不起作用?

android - 在哪里存储可以被任何android Activity 使用的jsonArray?

android - 摩托罗拉 MC40 无法识别 DataMatrix 代码中的西里尔符号

java - Head First Java Puzzle4(第 4 章,第 91 页)解释

android - Eclipse 无法识别 Android 设备

java - Junit 与 MockMVC - 错误 - java.lang.IllegalArgumentException : Entity must not be null

java - notify/notifyall 是否释放被持有的锁

java - 在哪里可以找到 Google 数据存储区的连接 URL?