我有一个音乐控制通知,允许用户开始/停止音乐。我想要与 Google Play 音乐应用程序通知完全相同的行为:播放音乐时,服务处于前台且通知不可取消,当音乐未播放时,服务不再处于前台且通知可以移除。它工作正常,但是当我取消我的服务的前台时,通知在重新出现之前很快被删除。
这是我的代码,首先是我如何构建通知:
NotificationCompat.Builder notifBuilder =
new android.support.v7.app.NotificationCompat.Builder(getApplicationContext())
.setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(1, 2, 3)
.setShowCancelButton(true)
.setCancelButtonIntent(deletePendingIntent)))
.setSmallIcon(R.drawable.notif_logo)
.setColor(ResourcesCompat.getColor(getResources(), R.color.blue, getTheme()))
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setShowWhen(false);
notifBuilder.setContentIntent(pendingIntent);
notifBuilder.setDeleteIntent(deletePendingIntent);
Run Code Online (Sandbox Code Playgroud)
这是我开始和更新通知的方式:
private void showNotification(NotificationCompat.Builder notifBuilder, boolean foreground) {
if (foreground) {
startForeground(NOTIFICATION_ID, notifBuilder.build());
} else {
stopForeground(false);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notifBuilder.build());
}
}
Run Code Online (Sandbox Code Playgroud)
如果我使用 stopForeground(false),通知在运行后仍然不可取消。如果我使用 stopForeground(true),通知会被快速删除然后再次添加,这会产生奇怪的闪烁。
如何在服务退出前台后可以取消通知,而不必删除然后再次添加通知?
我正在尝试测试订阅冷 observable 的部分代码。我的问题是单元测试在断言结果之前没有等待内部可观察调用结束,因此我的测试失败。
这是我要测试的代码:
public class UserManager {
private UserRepository userRepository;
private PublishSubject<List<User>> usersSubject = PublishSubject.create();
public UserManager(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Observable<List<User>> users() {
return usersSubject;
}
public void onUserIdsReceived(List<String> userIds) {
userRepository.getUsersInfo(userIds)
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<List<User>>() {
@Override
public void onSubscribe(@NonNull Disposable d) {}
@Override
public void onSuccess(@NonNull List<User> users) {
usersSubject.onNext(users);
}
@Override
public void onError(Throwable e) {}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的测试:
@RunWith(MockitoJUnitRunner::class)
class UserManagerTest {
private val userRepository = mock(UserRepository::class.java)
companion object {
@BeforeClass …Run Code Online (Sandbox Code Playgroud)