일반 알림 작성기는 Android O에 알림을 표시하지 않습니다.
Android 8 Oreo에 알림을 표시하려면 어떻게해야합니까?
Android O에 알림을 표시하기 위해 추가 할 새로운 코드가 있습니까?
일반 알림 작성기는 Android O에 알림을 표시하지 않습니다.
Android 8 Oreo에 알림을 표시하려면 어떻게해야합니까?
Android O에 알림을 표시하기 위해 추가 할 새로운 코드가 있습니까?
답변:
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
새로운 생성자와 관련이 없습니다 .
그리고 현재 26.0.2의 최신 AppCompat 라이브러리를 사용해야합니다
compile "com.android.support:appcompat-v7:26.0.+"
또한 공식 Android 문서를 확인할 수 있습니다
NotificationCompat.Builder(Context, String)
생성자 를 얻으려면 어떤 종속성 / 버전을 타겟팅해야 합니까? 나는 (무엇보다도) 사용하고 있습니다 : - compileSdkVersion 26
- buildToolsVersion '26.0.2'
- compile 'com.android.support:appcompat-v7:26.0.0-beta2'
그럼에도 불구하고 여전히 컨텍스트 및 문자열을 사용하여 내 생성자를 받아들이는 아닙니다. 어떤 아이디어?
여기에 의도 처리가있는 빠른 솔루션 기능을 게시합니다.
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- 베타 2 ( setChannelId
Compat Builder 를 호출 할 수 있도록 )
이 라이브러리 업데이트는 minSdkLevel을 14로 올리므로주의하십시오.
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;
}
}
26+ SDK 버전에서 푸시 알림을받을 수 없다면?
귀하의 솔루션은 다음과 같습니다.
public static void showNotification(Context context, String title, String messageBody) {
boolean isLoggedIn = SessionManager.getInstance().isLoggedIn();
Log.e(TAG, "User logged in state: " + isLoggedIn);
Intent intent = null;
if (isLoggedIn) {
//goto notification screen
intent = new Intent(context, MainActivity.class);
intent.putExtra(Extras.EXTRA_JUMP_TO, DrawerItems.ITEM_NOTIFICATION);
} else {
//goto login screen
intent = new Intent(context, LandingActivity.class);
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0 /* Request code */, intent, PendingIntent.FLAG_ONE_SHOT);
//Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
//Bitmap largeIcon = BitmapFactory.decodeResource(getResources(), R.drawable.ic_app_notification_icon);
String channel_id = createNotificationChannel(context);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context, channel_id)
.setContentTitle(title)
.setContentText(messageBody)
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageBody))
/*.setLargeIcon(largeIcon)*/
.setSmallIcon(R.drawable.app_logo_color) //needs white icon with transparent BG (For all platforms)
.setColor(ContextCompat.getColor(context, R.color.colorPrimaryDark))
.setVibrate(new long[]{1000, 1000})
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(pendingIntent)
.setPriority(Notification.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify((int) ((new Date(System.currentTimeMillis()).getTime() / 1000L) % Integer.MAX_VALUE) /* ID of notification */, notificationBuilder.build());
}
public static String createNotificationChannel(Context context) {
// NotificationChannels are required for Notifications on O (API 26) and above.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// The id of the channel.
String channelId = "Channel_id";
// The user-visible name of the channel.
CharSequence channelName = "Application_name";
// The user-visible description of the channel.
String channelDescription = "Application_name Alert";
int channelImportance = NotificationManager.IMPORTANCE_DEFAULT;
boolean channelEnableVibrate = true;
// int channelLockscreenVisibility = Notification.;
// Initializes NotificationChannel.
NotificationChannel notificationChannel = new NotificationChannel(channelId, channelName, channelImportance);
notificationChannel.setDescription(channelDescription);
notificationChannel.enableVibration(channelEnableVibrate);
// notificationChannel.setLockscreenVisibility(channelLockscreenVisibility);
// Adds NotificationChannel to system. Attempting to create an existing notification
// channel with its original values performs no operation, so it's safe to perform the
// below sequence.
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
assert notificationManager != null;
notificationManager.createNotificationChannel(notificationChannel);
return channelId;
} else {
// Returns null for pre-O (26) devices.
return null;
}
}
NotificationCompat.Builder notificationBuilder = 새로운 NotificationCompat.Builder (context, channel_id)
-> 여기 channel_id
에서 26+ SDK 버전으로 구성된 장치에서 푸시 알림을받습니다 .
-> NotificationCompat.Builder(context)
더 이상 사용되지 않는 메소드 이기 때문에 하나는 컨텍스트이고 다른 하나는 channel_id 인 두 개의 매개 변수가있는 업데이트 된 버전을 사용합니다.
-> NotificationCompat.Builder(context, channel_id)
업데이트 된 방법. 시도 해봐.
-> 26+ SDK 버전의 기기에서는 매번 channel_id를 생성합니다.
이 클래스를 사용하여 Android 8 알림
public class NotificationHelper {
private Context mContext;
private NotificationManager mNotificationManager;
private NotificationCompat.Builder mBuilder;
public static final String NOTIFICATION_CHANNEL_ID = "10001";
public NotificationHelper(Context context) {
mContext = context;
}
/**
* Create and push the notification
*/
public void createNotification(String title, String message)
{
/**Creates an explicit intent for an Activity in your app**/
Intent resultIntent = new Intent(mContext , SomeOtherActivity.class);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext,
0 /* Request code */, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder = new NotificationCompat.Builder(mContext);
mBuilder.setSmallIcon(R.mipmap.ic_launcher);
mBuilder.setContentTitle(title)
.setContentText(message)
.setAutoCancel(false)
.setSound(Settings.System.DEFAULT_NOTIFICATION_URI)
.setContentIntent(resultPendingIntent);
mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
notificationChannel.enableLights(true);
notificationChannel.setLightColor(Color.RED);
notificationChannel.enableVibration(true);
notificationChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
assert mNotificationManager != null;
mBuilder.setChannelId(NOTIFICATION_CHANNEL_ID);
mNotificationManager.createNotificationChannel(notificationChannel);
}
assert mNotificationManager != null;
mNotificationManager.notify(0 /* Request Code */, mBuilder.build());
}
}
이 코드를 사용해보십시오 :
public class FirebaseMessagingServices extends com.google.firebase.messaging.FirebaseMessagingService {
private static final String TAG = "MY Channel";
Bitmap bitmap;
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
Utility.printMessage(remoteMessage.getNotification().getBody());
// Check if message contains a data payload.
if (remoteMessage.getData().size() > 0) {
Log.d(TAG, "Message data payload: " + remoteMessage.getData());
String title = remoteMessage.getData().get("title");
String body = remoteMessage.getData().get("body");
String message = remoteMessage.getData().get("message");
String imageUri = remoteMessage.getData().get("image");
String msg_id = remoteMessage.getData().get("msg-id");
Log.d(TAG, "1: " + title);
Log.d(TAG, "2: " + body);
Log.d(TAG, "3: " + message);
Log.d(TAG, "4: " + imageUri);
if (imageUri != null)
bitmap = getBitmapfromUrl(imageUri);
}
sendNotification(message, bitmap, title, msg_id);
}
}
private void sendNotification(String message, Bitmap image, String title,String msg_id) {
int notifyID = 0;
try {
notifyID = Integer.parseInt(msg_id);
} catch (NumberFormatException e) {
e.printStackTrace();
}
String CHANNEL_ID = "my_channel_01"; // The id of the channel.
Intent intent = new Intent(this, HomeActivity.class);
intent.putExtra("title", title);
intent.putExtra("message", message);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "01")
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_notification)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText(message))
.setContentText(message)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setChannelId(CHANNEL_ID)
.setContentIntent(pendingIntent);
if (image != null) {
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle() //Set the Image in Big picture Style with text.
.bigPicture(image)
.setSummaryText(message)
.bigLargeIcon(null));
}
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // For Oreo and greater than it, we required Notification Channel.
CharSequence name = "My New Channel"; // The user-visible name of the channel.
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID,name, importance); //Create Notification Channel
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(notifyID /* ID of notification */, notificationBuilder.build());
}
public Bitmap getBitmapfromUrl(String imageUrl) { //This method returns the Bitmap from Url;
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
더 낮은 API 버전뿐만 아니라 Android O 용 Android 알림 데모 앱. 다음은 GitHub-Demo 1 및 GitHub-Demo 2 에 대한 최고의 데모 앱입니다 .
이것은 firebase api 버전 11.8.0의 버그이므로 API 버전을 줄이면이 문제에 직면하지 않습니다.
Oreo에서 동일한 문제가 발생하여 NotificationManager.IMPORTANCE_NONE으로 채널을 만든 다음 나중에 업데이트하면 채널이 원래 중요도 수준을 유지한다는 것을 알았습니다.
이것은 다음과 같은 Google 알림 교육 문서에 의해 백업됩니다 .
알림 채널을 만든 후에는 알림 동작을 변경할 수 없습니다. 사용자는 해당 시점에서 완전한 제어 권한을 갖습니다.
앱을 제거했다가 다시 설치하면 채널 동작을 재설정 할 수 있습니다.
해당 채널에 대한 알림을 표시하지 않으려면 (예 : 자동 알림 사용) IMPORTANCE_NONE을 사용하지 않는 것이 좋습니다.
방법은 다음과 같습니다.
private fun sendNotification() {
val notificationId = 100
val chanelid = "chanelid"
val intent = Intent(this, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
val pendingIntent = PendingIntent.getActivity(this, 0, intent, 0)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // you must create a notification channel for API 26 and Above
val name = "my channel"
val description = "channel description"
val importance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(chanelid, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
val notificationManager = getSystemService(NotificationManager::class.java)
notificationManager.createNotificationChannel(channel)
}
val mBuilder = NotificationCompat.Builder(this, chanelid)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("Want to Open My App?")
.setContentText("Open my app and see good things")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true) // cancel the notification when clicked
.addAction(R.drawable.ic_check, "YES", pendingIntent) //add a btn to the Notification with a corresponding intent
val notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(notificationId, mBuilder.build());
}
=> https://developer.android.com/training/notify-user/build-notification 에서 전체 자습서를 읽으십시오.
CHANNEL_ID
에 NotificationChannel 및 Notification.Builder가 동일해야합니다,이 코드를 시도 :
String CHANNEL_ID = "my_channel_01";
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "Solveta Unread", NotificationManager.IMPORTANCE_DEFAULT);
Notification.Builder notification = new Notification.Builder(getApplicationContext(), CHANNEL_ID);
내 경우에는 Android 8.1.0 및 모델 번호 vivo1811 이 있고 위의 모든 솔루션으로 시도했지만 아무것도 작동하지 않습니다.
그래서 마지막으로 Firebase 지원에 글을 작성한 다음 추가 디버깅시 "앱 중지로 브로드 캐스트하지 못했습니다"라는 메시지가 표시 됩니다. 앱이 강제 종료되지 않았는지 확인하십시오 .
그리고 이것은 Firebase 팀의 답변입니다->
이것은 일부 OEM이 구현 한 배터리 최적화로 인해 알려진 문제입니다. 앱이 앱 스위처에서 스 와이프되면 애플리케이션은 강제 종료 된 것처럼 처리되며 이는 기본 Android 동작이 아닙니다. 불행한 부작용은 앱의 FCM 서비스 실행이 중지 될 수 있다는 것입니다. 현재이 동작을 개선하기 위해 노력하고 있지만 실제 수정은 OEM 측에서 수행해야합니다.
여기서 OEM은 Original Equipment Manufacturer를 의미합니다 .
위의 솔루션을 시도한 후 이로 인해 어려움을 겪고있는 사람은 알림 채널을 작성할 때 사용 된 채널 ID가 알림 빌더에서 설정 한 채널 ID와 동일한 지 확인 하십시오.
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)
private void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher_background)
.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);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O)
{
NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
nChannel.enableLights(true);
assert manager != null;
builder.setChannelId(NOTIFICATION_CHANNEL_ID);
manager.createNotificationChannel(nChannel);
}
assert manager != null;
manager.notify(0, builder.build());
}
다음 방법은 것 알림을 보여 큰 텍스트와 동결 (알림 심지어 사용자 와이프 후 제거되지 않습니다)를 활성화 필요. NotificationManager 서비스가 필요합니다
public static void showNotificationOngoing(Context context,String title) {
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(context)
.setContentTitle(title + DateFormat.getDateTimeInstance().format(new Date()) + ":" + accuracy)
.setContentText(addressFragments.toString())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(contentIntent)
.setOngoing(true)
.setStyle(new Notification.BigTextStyle().bigText(addressFragments.toString()))
.setAutoCancel(true);
notificationManager.notify(3, notificationBuilder.build());
}
알림 을 제거하는 방법
public static void removeNotification(Context context){
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancelAll();
}
소스 링크
fun pushNotification(message: String?, clickAtion: String?) {
val ii = Intent(clickAtion)
ii.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
val pendingIntent = PendingIntent.getActivity(this, REQUEST_CODE, ii, PendingIntent.FLAG_ONE_SHOT)
val soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val largIcon = BitmapFactory.decodeResource(applicationContext.resources,
R.mipmap.ic_launcher)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val channelId = "default_channel_id"
val channelDescription = "Default Channel"
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
var notificationChannel = notificationManager.getNotificationChannel(channelId)
if (notificationChannel != null) {
val importance = NotificationManager.IMPORTANCE_HIGH //Set the importance level
notificationChannel = NotificationChannel(channelId, channelDescription, importance)
// notificationChannel.lightColor = Color.GREEN //Set if it is necesssary
notificationChannel.enableVibration(true) //Set if it is necesssary
notificationManager.createNotificationChannel(notificationChannel)
val noti_builder = NotificationCompat.Builder(this)
.setContentTitle("MMH")
.setContentText(message)
.setSmallIcon(R.drawable.ic_launcher_background)
.setChannelId(channelId)
.build()
val random = Random()
val id = random.nextInt()
notificationManager.notify(id,noti_builder)
}
}
else
{
val notificationBuilder = NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher).setColor(resources.getColor(R.color.colorPrimary))
.setVibrate(longArrayOf(200, 200, 0, 0, 0))
.setContentTitle(getString(R.string.app_name))
.setLargeIcon(largIcon)
.setContentText(message)
.setAutoCancel(true)
.setStyle(NotificationCompat.BigTextStyle().bigText(message))
.setSound(soundUri)
.setContentIntent(pendingIntent)
val random = Random()
val id = random.nextInt()
notificationManager.notify(id, notificationBuilder.build())
}
}
아래 코드는 Oreo에서 나를 위해 작동합니다.이를 시도 할 수 있습니다. 그것이 당신을 위해 작동하기를 바랍니다
private void sendNotification (컨텍스트 ctx, 문자열 제목, int notificationNumber, 문자열 메시지, 문자열 서브 텍스트, 의도 의도) {
try {
PendingIntent pendingIntent = PendingIntent.getActivity(ctx, notificationNumber, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
Uri url = null;
NotificationCompat.Builder notificationBuilder = null;
try {
if (Build.VERSION.SDK_INT >= 26) {
try{
NotificationManager notificationManager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.deleteNotificationChannel(CHANNEL_ID_1);
notificationManager.deleteNotificationChannel(CHANNEL_ID_2);
if(!intent.getStringExtra("type").equalsIgnoreCase(""+TYPE_REQUEST)){
NotificationChannel breaking = new NotificationChannel(CHANNEL_ID_1, CHANNEL_ID_1_NAME, NotificationManager.IMPORTANCE_HIGH);
breaking.setShowBadge(false);
breaking.enableLights(true);
breaking.enableVibration(true);
breaking.setLightColor(Color.WHITE);
breaking.setVibrationPattern(new long[]{100, 200, 100, 200, 100, 200, 100});
breaking.setSound(url,new AudioAttributes.Builder().build());
notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_1)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.createNotificationChannel(breaking);
}else{
NotificationChannel politics = new NotificationChannel(CHANNEL_ID_2,CHANNEL_ID_2_NAME, NotificationManager.IMPORTANCE_DEFAULT);
politics.setShowBadge(false);
politics.enableLights(true);
politics.enableVibration(true);
politics.setLightColor(Color.BLUE);
politics.setVibrationPattern(new long[]{100, 200, 100, 200, 100});
politics.setSound(url,new AudioAttributes.Builder().build());
notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID_2)
.setSmallIcon(R.mipmap.ic_launcher);
notificationManager.createNotificationChannel(politics);
}
}catch (Exception e){
e.printStackTrace();
}
} else {
notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher);
}
} catch (Exception e) {
e.printStackTrace();
}
if (notificationBuilder == null) {
notificationBuilder = new NotificationCompat.Builder(ctx)
.setSmallIcon(R.mipmap.ic_launcher);
}
notificationBuilder.setContentTitle(title);
notificationBuilder.setSubText(subtext);
notificationBuilder.setAutoCancel(true);
notificationBuilder.setContentIntent(pendingIntent);
notificationBuilder.setNumber(notificationNumber);
NotificationManager notificationManager =
(NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationNumber, notificationBuilder.build());
} catch (Exception e) {
e.printStackTrace();
}
}
Android Oreo에서 알림 앱은 채널 및 NotificationHelper 클래스를 사용하여 수행되며 채널 ID와 채널 이름이 있어야합니다.
먼저 NotificationHelper 클래스를 만들어야합니다
public class NotificationHelper extends ContextWrapper {
private static final String EDMT_CHANNEL_ID="com.example.safna.notifier1.EDMTDEV";
private static final String EDMT_CHANNEL_NAME="EDMTDEV Channel";
private NotificationManager manager;
public NotificationHelper(Context base)
{
super(base);
createChannels();
}
private void createChannels()
{
NotificationChannel edmtChannel=new NotificationChannel(EDMT_CHANNEL_ID,EDMT_CHANNEL_NAME,NotificationManager.IMPORTANCE_DEFAULT);
edmtChannel.enableLights(true);
edmtChannel.enableVibration(true);
edmtChannel.setLightColor(Color.GREEN);
edmtChannel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
getManager().createNotificationChannel(edmtChannel);
}
public NotificationManager getManager()
{
if (manager==null)
manager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
return manager;
}
public NotificationCompat.Builder getEDMTChannelNotification(String title,String body)
{
return new NotificationCompat.Builder(getApplicationContext(),EDMT_CHANNEL_ID)
.setContentText(body)
.setContentTitle(title)
.setSmallIcon(R.mipmap.ic_launcher_round)
.setAutoCancel(true);
}
}
활동 xml 파일에서 단추를 작성한 다음 기본 활동에서
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper=new NotificationHelper(this);
btnSend=(Button)findViewById(R.id.btnSend);
btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String title="Title";
String content="Content";
Notification.Builder builder=helper.getEDMTChannelNotification(title,content);
helper.getManager().notify(new Random().nextInt(),builder.build());
}
});
}
그런 다음 ur 프로젝트를 실행하십시오.
26 (oreo) 이상의 API 레벨에 대한 알림 채널을 작성해야합니다.
`NotificationChannel channel = new NotificationChannel(STRING_ID,CHANNEL_NAME,NotificationManager.IMPORTANCE_HIGH);
STRING_ID = 문자열 알림 channelid는 Notification.Builder와 동일합니다.
`Notification notification = new Notification.Builder(this,STRING_ID)
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Hello Notification")
.setContentText("It is Working")
.setContentIntent(pendingIntent)
.build();`
알림과 알림의 채널 ID는 동일해야합니다. 전체 코드는 다음과 같습니다.`
@RequiresApi(api = Build.VERSION_CODES.O)
private void callNotification2() {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,11,
intent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this,"22")
.setSmallIcon(android.R.drawable.ic_menu_help)
.setContentTitle("Hello Notification")
.setContentText("It is Working")
.setContentIntent(pendingIntent)
.build();
NotificationChannel channel = new
NotificationChannel("22","newName",NotificationManager.IMPORTANCE_HIGH);
NotificationManager manager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
manager.createNotificationChannel(channel);
manager.notify(11,notification);
}'
우선, Android Oreo, 즉 API 레벨 26에서 모르는 경우 알림을 채널로 예약해야합니다.
이 경우 많은 튜토리얼이 오레오와 아래의 알림에 대해 다른 예를 보여주기 때문에 혼란 스러울 수 있습니다.
여기 오레오 위와 아래에서 실행되는 일반적인 코드가 있습니다.
String CHANNEL_ID = "MESSAGE";
String CHANNEL_NAME = "MESSAGE";
NotificationManagerCompat manager = NotificationManagerCompat.from(MainActivity.this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME,
NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
Notification notification = new NotificationCompat.Builder(MainActivity.this,CHANNEL_ID)
.setSmallIcon(R.drawable.ic_android_black_24dp)
.setContentTitle(TitleTB.getText().toString())
.setContentText(MessageTB.getText().toString())
.build();
manager.notify(getRandomNumber(), notification); // In case you pass a number instead of getRandoNumber() then the new notification will override old one and you wont have more then one notification so to do so u need to pass unique number every time so here is how we can do it by "getRandoNumber()"
private static int getRandomNumber() {
Date dd= new Date();
SimpleDateFormat ft =new SimpleDateFormat ("mmssSS");
String s=ft.format(dd);
return Integer.parseInt(s);
}
비디오 자습서 : YOUTUBE VIDEO
이 데모를 다운로드하려는 경우 : GitHub Link
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());