“设置”、“应用程序”和“运行”下有 1 个进程和 0 个服务

问题描述 投票:0回答:1
java android kotlin android-service
1个回答
0
投票

在 Android 中使用前台服务时,需要在 onStartCommand() 方法中调用 startForeground() 来向用户提供持久通知。此通知通知用户您的应用程序正在运行前台服务,并有助于防止系统意外终止服务。

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this, R.raw.ringtone);
player.start();

// Create a notification for the foreground service
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
    .setContentTitle("Foreground Service")
    .setContentText("Service is running...")
    .setSmallIcon(R.drawable.ic_example)
    .build();

// Start the service as a foreground service
startForeground(NOTIFICATION_ID, notification);

return START_NOT_STICKY;

}

© www.soinside.com 2019 - 2024. All rights reserved.