importandroid.app.Notification;importandroid.app.NotificationChannel;importandroid.app.NotificationManager;importandroid.app.Service;importandroid.content.Context;importandroid.content.Intent;importandroid.graphics.Color;importandroid.os.Build;importandroid.os.IBinder;importandroid.support.annotation.RequiresApi;importandroid.support.v4.app.NotificationCompat;importcom.demo.badges.IconBadgeNumManager;public class MyService extendsService {

IconBadgeNumManager setIconBadgeNumManager;private booleanisStop;private intcount;

Thread thread= new Thread(newRunnable() {

@Overridepublic voidrun() {while (!isStop) {try{

Thread.sleep(1000);

}catch(InterruptedException e) {

e.printStackTrace();

}

count+= 2;

sendIconNumNotification();

}

}

});publicMyService() {

setIconBadgeNumManager= newIconBadgeNumManager();

}

@Overridepublic int onStartCommand(Intent intent, int flags, intstartId) {

isStop= false;

thread.start();return super.onStartCommand(intent, flags, startId);

}

@Overridepublic voidonDestroy() {super.onDestroy();

isStop= true;

}

@OverridepublicIBinder onBind(Intent intent) {throw new UnsupportedOperationException("Not yet implemented");

}private voidsendIconNumNotification() {

NotificationManager nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);if (nm == null) return;

String notificationChannelId= null;if (android.os.Build.VERSION.SDK_INT >=android.os.Build.VERSION_CODES.O) {

NotificationChannel notificationChannel=createNotificationChannel();

nm.createNotificationChannel(notificationChannel);

notificationChannelId=notificationChannel.getId();

}

Notification notification= null;try{

notification= new NotificationCompat.Builder(this, notificationChannelId)

.setSmallIcon(getApplicationInfo().icon)

.setWhen(System.currentTimeMillis())

.setContentTitle("title")

.setContentText("content num: " +count)

.setTicker("ticker")

.setAutoCancel(true)

.setNumber(count)

.build();

notification=setIconBadgeNumManager.setIconBadgeNum(getApplication(), notification, count);

nm.notify(32154, notification);

}catch(Exception e) {

e.printStackTrace();

}

}

@RequiresApi(api=Build.VERSION_CODES.O)private staticNotificationChannel createNotificationChannel() {

String channelId= "test";

NotificationChannel channel= null;

channel= newNotificationChannel(channelId,"Channel1", NotificationManager.IMPORTANCE_DEFAULT);

channel.enableLights(true); //是否在桌面icon右上角展示小红点

channel.setLightColor(Color.RED); //小红点颜色

channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知

returnchannel;

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐