由于Android 12中对前台服务的限制更加严格,因此需要进行特殊设置。
具体代码如下:
在 AndroidManifest.xml 文件中,需要添加以下代码:
其中,foregroundServiceType可以选择location、dataSync、mediaPlayback这三个其中的一个。根据实际需求来选择,其中"location"是基于位置的服务,"dataSync"是基于数据的同步服务,而"mediaPlayback"是基于媒体的播放服务。
在启动前台服务时,需要使用startForegroundService()方法,然后调用startForeground()方法为服务设置通知图标和文本。
示例代码如下:
Intent serviceIntent = new Intent(this, MyForegroundService.class); ContextCompat.startForegroundService(this, serviceIntent);
MyForegroundService.java:
public class MyForegroundService extends Service {
...
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
...
Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.ic_notification)
.build();
startForeground(1, notification);
return START_STICKY;
}
}