Я обнаружил, что использую устаревший метод для noficitations (notification.setLatestEventInfo())
Он говорит, что использует Notification.Builder.
Когда я пытаюсь создать новый экземпляр, он сообщает мне:
Notification.Builder cannot be resolved to a type
Это в API 11, поэтому, если вы разрабатываете что-либо раньше, чем 3.0, вы должны продолжать использовать старый API.
Обновить: класс NotificationCompat.Builder добавлен в пакет поддержки, поэтому мы можем использовать его для поддержки уровня API v4 и выше:
http://developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html
Notification.Builder API 11 или NotificationCompat.Builder API 1
Это пример использования.
Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
YOUR_PI_REQ_CODE, notificationIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx
.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.some_img)
.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
.setTicker(res.getString(R.string.your_ticker))
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(res.getString(R.string.your_notif_title))
.setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();
nm.notify(YOUR_NOTIF_ID, n);
Notification.Builder
. Я делал то, что они говорили, но это не имело никакого смысла. Я прихожу сюда и вижу, что это не так. Я действительно ценю ваш ответ, поскольку он заставил меня осознать ошибку, допущенную в документе.
в дополнение к выбранному ответу здесь приведен пример кода класса NotificationCompat.Builder
из Исходные трюки:
// Add app running notification
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notifications Example")
.setContentText("This is a test notification");
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}
// Remove notification
private void removeNotification() {
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(FM_NOTIFICATION_ID);
}
Notification Builder предназначен исключительно для Android API уровня 11 и выше (Android 3.0 и выше).
Следовательно, если вы не нацеливаете на планшеты Honeycomb, вы не должны использовать построитель уведомлений, а скорее следуйте более старым методам создания уведомлений, например следующим example.
Подробнее см. Уведомления об обновлениях".
Android N также позволяет связать похожие уведомления, чтобы они отображались как одно уведомление. Чтобы сделать это возможным, Android N использует существующий метод
NotificationCompat.Builder.setGroup()
. Пользователи могут расширять каждое из уведомлений и выполнять такие действия, как ответ и отклонять каждое из уведомлений, отдельно от уведомление оттенок.Это уже существующий образец, который показывает простой сервис, который отправляет уведомления с помощью NotificationCompat. Каждый непрочитанный разговор из пользователь отправляется как отдельное уведомление.
Этот образец обновлен, чтобы воспользоваться новым уведомлением функции доступны в Android N.
У меня возникли проблемы с созданием уведомлений (только для Android 4.0+). Эта ссылка показала мне, что я делаю неправильно, и говорит следующее:
Required notification contents
A Notification object must contain the following:
A small icon, set by setSmallIcon()
A title, set by setContentTitle()
Detail text, set by setContentText()
В основном я отсутствовал один из них. Как основа для устранения неполадок с этим, убедитесь, что у вас есть все это, по крайней мере. Надеюсь, это спасет кого-то еще головную боль.
Я использовал
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Firebase Push Notification")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
Он работает даже в API 8 вы можете использовать этот код:
Notification n =
new Notification(R.drawable.yourownpicturehere, getString(R.string.noticeMe),
System.currentTimeMillis());
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyActivity.class),
0);
n.setLatestEventInfo(getApplicationContext(), getString(R.string.title), getString(R.string.message), i);
n.number=++count;
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.flags |= Notification.DEFAULT_SOUND;
n.flags |= Notification.DEFAULT_VIBRATE;
n.ledARGB = 0xff0000ff;
n.flags |= Notification.FLAG_SHOW_LIGHTS;
// Now invoke the Notification Service
String notifService = Context.NOTIFICATION_SERVICE;
NotificationManager mgr =
(NotificationManager) getSystemService(notifService);
mgr.notify(NOTIFICATION_ID, n);
Или я предлагаю следовать отличному tutorial об этом
В случае, если это помогает кому-то... У меня возникли проблемы с настройкой уведомлений с помощью пакета поддержки при тестировании более старых API. Я смог заставить их работать на более новом устройстве, но получил бы тестирование ошибок на старом устройстве. Что, наконец, заработало для меня, это удалить все импортные функции, связанные с функциями уведомления. В частности, NotificationCompat и TaskStackBuilder. Кажется, что при настройке моего кода вначале импортируются, добавленные из новой сборки, а не из пакета поддержки. Затем, когда я захотел реализовать эти элементы позже в eclipse, мне не было предложено импортировать их снова. Надеюсь, что это имеет смысл, и что это помогает кому-то другому:)
Автономный пример
Тот же метод, что и в этом ответе, но:
Источник:
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class Main extends Activity {
private int i;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("click me");
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final Notification notification = new Notification.Builder(Main.this)
/* Make app open when you click on the notification. */
.setContentIntent(PendingIntent.getActivity(
Main.this,
Main.this.i,
new Intent(Main.this, Main.class),
PendingIntent.FLAG_CANCEL_CURRENT))
.setContentTitle("title")
.setAutoCancel(true)
.setContentText(String.format("id = %d", Main.this.i))
// Starting on Android 5, only the alpha channel of the image matters.
// https://stackoverflow.com/a/35278871/895245
// `android.R.drawable` resources all seem suitable.
.setSmallIcon(android.R.drawable.star_on)
// Color of the background on which the alpha image wil drawn white.
.setColor(Color.RED)
.build();
final NotificationManager notificationManager =
(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(Main.this.i, notification);
// If the same ID were used twice, the second notification would replace the first one.
//notificationManager.notify(0, notification);
Main.this.i++;
}
});
this.setContentView(button);
}
}
Протестировано в Android 22.
// This is a working Notification
private static final int NotificID=01;
b= (Button) findViewById(R.id.btn);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Notification notification=new Notification.Builder(MainActivity.this)
.setContentTitle("Notification Title")
.setContentText("Notification Description")
.setSmallIcon(R.mipmap.ic_launcher)
.build();
NotificationManager notificationManager=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notification.flags |=Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(NotificID,notification);
}
});
}