用service写一个完整的通知代码,java
时间: 2024-01-03 17:04:16 浏览: 57
好的,下面是一个使用Service来创建通知的Java代码示例:
```java
public class NotificationService extends Service {
private static final String CHANNEL_ID = "my_channel";
private static final int NOTIFICATION_ID = 1;
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
showNotification();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"My Channel",
NotificationManager.IMPORTANCE_DEFAULT);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
private void showNotification() {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, notificationIntent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this, CHANNEL_ID)
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("My Notification")
.setContentText("This is a notification from my app")
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat manager = NotificationManagerCompat.from(this);
manager.notify(NOTIFICATION_ID, builder.build());
}
}
```
这个服务会在启动时创建一个通知渠道,并且在 onStartCommand() 方法中调用 showNotification() 方法来显示一个简单的通知。在这个示例中,通知中包含应用程序的图标、标题和文本,以及一个点击通知时启动的MainActivity。通知还被设置为自动取消,这意味着用户可以通过单击通知来将其删除。