用service写一个通知代码,java
时间: 2024-01-03 11:04:16 浏览: 32
好的,以下是一个使用Service实现通知的示例代码:
```java
public class NotificationService extends Service {
private NotificationManager mNotificationManager;
private static final int NOTIFICATION_ID = 1;
private static final String CHANNEL_ID = "NotificationChannel";
@Override
public void onCreate() {
super.onCreate();
// 创建通知管理器
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 构建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("通知标题")
.setContentText("通知内容")
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
// 创建通知渠道(Android 8.0及以上系统需要使用通知渠道)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "通知渠道", NotificationManager.IMPORTANCE_DEFAULT);
mNotificationManager.createNotificationChannel(channel);
}
// 显示通知
mNotificationManager.notify(NOTIFICATION_ID, builder.build());
// START_STICKY表示Service被杀死后会自动重启
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
// 关闭通知
mNotificationManager.cancel(NOTIFICATION_ID);
}
}
```
在上述代码中,我们创建了一个名为`NotificationService`的Service,它继承自`Service`类。在`onCreate`方法中,我们创建了一个`NotificationManager`对象,用来管理通知。在`onStartCommand`方法中,我们使用`NotificationCompat.Builder`构建了一个通知,并通过`mNotificationManager.notify`方法显示通知。如果系统版本在Android 8.0及以上,我们还需要创建一个通知渠道。在`onDestroy`方法中,我们通过`mNotificationManager.cancel`方法关闭通知。
注意:在AndroidManifest.xml文件中,需要注册服务并添加通知权限:
```xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application ...>
<service android:name=".NotificationService" />
...
</application>
</manifest>
```
希望这个示例代码能对你有所帮助。