Хороший вопрос!
После нескольких (жестких) дебатов с моими товарищами по команде + мой опыт работы с приложениями MVC я бы не рекомендовал передавать viewmodel на ваш уровень сервиса / домена.
В противном случае ваш сервисный уровень окажется непригодным для использования, потому что ограничено вашими viewModels, которые являются специфическими для одного вида.
Хорошие инструменты, такие как https: / /github.com/AutoMapper/AutoMapper, чтобы выполнить задание сопоставления.
В Android O необходимо использовать канал с вашим Notification Builder
ниже, это пример кода:
// Sets an ID for the notification, so it can be updated.
int notifyID = 1;
String CHANNEL_ID = "my_channel_01";// The id of the channel.
CharSequence name = getString(R.string.channel_name);// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
// Create a notification and set the notification channel.
Notification notification = new Notification.Builder(MainActivity.this)
.setContentTitle("New Message")
.setContentText("You've received new messages.")
.setSmallIcon(R.drawable.ic_notify_status)
.setChannelId(CHANNEL_ID)
.build();
Или с использованием совместимости по:
NotificationCompat notification =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setChannelId(CHANNEL_ID).build();
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.createNotificationChannel(mChannel);
// Issue the notification.
mNotificationManager.notify(notifyID , notification);
или если вы хотите просто исправить, используйте следующий код:
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mNotificationManager.createNotificationChannel(mChannel);
}
Обновления: Ссылка NotificationCompat.Builder
NotificationCompat.Builder(Context context)
Этот конструктор устарел на уровне API 26.0.0, поэтому вы должны использовать
Builder(Context context, String channelId)
, поэтому нет необходимости в setChannelId
с новым конструктором.
И вы должны использовать последняя из библиотеки AppCompat в настоящее время 26.0.2
compile "com.android.support:appcompat-v7:26.0.+"
Источник из Канал разработчиков Android на Youtube
Кроме того, вы можете проверить официальные Android-документы
Здесь я размещаю некоторую функцию быстрого решения с обработкой намерений
public void showNotification(Context context, String title, String body, Intent intent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
int notificationId = 1;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel mChannel = new NotificationChannel(
channelId, channelName, importance);
notificationManager.createNotificationChannel(mChannel);
}
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(title)
.setContentText(body);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(intent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
notificationManager.notify(notificationId, mBuilder.build());
}
В дополнение к этому ответу вам нужно создать канал уведомления, прежде чем он сможет быть использован.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
/* Create or update. */
NotificationChannel channel = new NotificationChannel("my_channel_01",
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
Также вам нужно использовать каналы только в том случае, если ваша targetSdkVersion 26 или выше.
Если вы используете NotificationCompat.Builder, вам также необходимо обновить бета-версию библиотеки поддержки: https://developer.android.com/topic/libraries/ support-library / revisions.html # 26-0-0-beta2 (чтобы иметь возможность вызвать setChannelId
в компоновщике сопоставления.)
Будьте осторожны, так как это обновление библиотеки повышает minSdkLevel до 14.
Для тех, кто борется с этим, попробовав вышеуказанные решения, убедитесь, что идентификатор канала, используемый при создании канала уведомлений, идентичен идентификатору канала, установленному в конструкторе уведомлений.
const val CHANNEL_ID = "EXAMPLE_CHANNEL_ID"
// create notification channel
val notificationChannel = NotificationChannel(CHANNEL_ID,
NOTIFICATION_NAME, NotificationManager.IMPORTANCE_HIGH)
// building notification
NotificationCompat.Builder(context)
.setSmallIcon(android.R.drawable.ic_input_add)
.setContentTitle("Title")
.setContentText("Subtitle")
.setPriority(NotificationCompat.PRIORITY_MAX)
.setChannelId(CHANNEL_ID)
Это ошибка в firebase api версии 11.8.0. Поэтому, если вы уменьшите версию API, вы не столкнетесь с этой проблемой.
public class MyFirebaseMessagingServices extends FirebaseMessagingService {
private NotificationChannel mChannel;
private NotificationManager notifManager;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
if (remoteMessage.getData().size() > 0) {
try {
JSONObject jsonObject = new JSONObject(remoteMessage.getData());
displayCustomNotificationForOrders(jsonObject.getString("title"), jsonObject.getString("description"));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
private void displayCustomNotificationForOrders(String title, String description) {
if (notifManager == null) {
notifManager = (NotificationManager) getSystemService
(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationCompat.Builder builder;
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent;
int importance = NotificationManager.IMPORTANCE_HIGH;
if (mChannel == null) {
mChannel = new NotificationChannel
("0", title, importance);
mChannel.setDescription(description);
mChannel.enableVibration(true);
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(this, "0");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentTitle(title)
.setSmallIcon(getNotificationIcon()) // required
.setContentText(description) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setLargeIcon(BitmapFactory.decodeResource
(getResources(), R.mipmap.logo))
.setBadgeIconType(R.mipmap.logo)
.setContentIntent(pendingIntent)
.setSound(RingtoneManager.getDefaultUri
(RingtoneManager.TYPE_NOTIFICATION));
Notification notification = builder.build();
notifManager.notify(0, notification);
} else {
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = null;
pendingIntent = PendingIntent.getActivity(this, 1251, intent, PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(description)
.setAutoCancel(true)
.setColor(ContextCompat.getColor(getBaseContext(), R.color.colorPrimary))
.setSound(defaultSoundUri)
.setSmallIcon(getNotificationIcon())
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().setBigContentTitle(title).bigText(description));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(1251, notificationBuilder.build());
}
}
private int getNotificationIcon() {
boolean useWhiteIcon = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP);
return useWhiteIcon ? R.mipmap.logo : R.mipmap.logo;
}
}
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CHANNEL_ID")
........
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "Hello";// The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
mNotificationManager.createNotificationChannel(mChannel);
}
mNotificationManager.notify(notificationId, notificationBuilder.build());
NotificationCompat.Builder(Context, String)
? Я использую (между прочим): -compileSdkVersion 26
-buildToolsVersion '26.0.2'
-compile 'com.android.support:appcompat-v7:26.0.0-beta2'
, и все же он все еще не принимает мой конструктор, используя Context и String. Есть идеи? – Loisaida Sam 12 October 2017 в 03:35